본문 바로가기
파이썬

파이썬 공부하기_모듈 만들고 불러보기 ( if __name__ == "__main__" )

by 혜룐 2015. 11. 10.
https://wikidocs.net/29
mod1.py이라는 파일에
sum 이라는 함수만 정의하기
python 인터프리터를 실행>
import 모듈이름
(= 모듈이름이란, .py 확장자를 제거한 mod1만을 말함)
함수 sum이 제대로 동작하는지
호출해
보기
[root@tpl-master module]# cat mod1.py
def sum(a,b):
return a+b
[root@iaas-dms2-mysql-tpl-master module]# python
Python 2.6.4 (r264:75706, Oct 23 2012, 16:21:35) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
import mod1
>>>
print mod1.sum(9,11)
20
>>>다른 타입의 객체끼리 더하는 것을 방지 하기
print mod2.sum(1,'a') -->실행결과 : TypeError: unsupported operand type(s) for +: 'int' and 'str'
safe_sum 함수를 만들어,
타입체크 후
같은 타입이면, sum
을 하도록 수정한다.
[root@tpl-master module]# cat mod2.py
def sum(a,b):
return a+b 
def safe_sum(a,b):
if type(a) != type(b):
print "Error"
return
else:
return sum(a,b)
>>>import mod2
>>>print mod2.sum(1,2)
3
>>>print mod2.sum(1,'a')
Traceback (most recent call last):
File "<stdin>", line 1, in<module>
File "mod2.py", line 2, in sum
return a+b
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>>>>print mod2.safe_sum(1,2)
3
>>>print mod2.safe_sum(1,'a')
Error
None
>>>
from 모듈이름 import 모듈함수
모듈이름을 붙이지 않고, 바로 해당 모듈의 함수를 쓸수 있다. ( print mod2.sum(1,2) 가 아니라
print sum(1,2) 로 호출
)
선언되지 않은 경우에는 NameError: name 'safe_sum' is not defined
라는 에러를 뱉는다.
위의 경우에는
from mod2 import sum, safe_sum
from mod2 import *
[root@tpl-master module]# python
Python 2.6.4 (r264:75706, Oct 23 2012, 16:21:35) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>>>>import mod2
>>>print mod2.sum(1,2)
3
>>>>>>
from mod2 import sum
>>>print
sum(2,3)
5
>>>print mod2.safe_sum(1,2)
3
>>>
print safe_sum(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in<module>
NameError: name 'safe_sum' is not defined
>>>>>>
from mod2 import sum, safe_sum
>>>
print safe_sum(1,2)
3
>>>print sum(1,2)
3
>>>
if __name__ == "__main__" 
파이썬파일을 직접 실행 시켰을때와, 인터프리터나 다른 파일에서 모듈을 불러서 사용할때 체크 하는 방법
파이썬 모듈을 만든 다음,
보통 그 모듈을 테스트하기 위해
위와 같은 방법을 쓴단다.
[root@tpl-master module]# cat mod3.py 
def sum(a,b):
return a+b 
def safe_sum(a,b):
if type(a) != type(b):
print "Error"
return 
else:
return sum(a,b)
if __name__ == "__main__":
print safe_sum('a',1)
print safe_sum(0,1)
인터프리터로 실행할때는 False
가 되기때문에, if 조건에 맞지 않아 아래 print 문이 수행되지 않는다.
[root@tpl-master module]# python
Python 2.6.4 (r264:75706, Oct 23 2012, 16:21:35) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>from mod3 import *
>>>print safe_sum('a',2)
Error
None
>>>quit()