Python의 모듈 대해 알아봅니다.
# mod1.py
def add(a, b):
return a + b
def sub(a, b):
return a-b
# 이 mod1.py 파일이 바로 모듈이다.
importimport mod1
print(mod1.add(3, 4)) # 7
print(mod1.sub(4, 2)) # 2
import 모듈_이름from 모듈_이름 import 모듈_함수from 모듈_이름 import 모듈_함수
from 모듈_이름 import 모듈_함수1, 모듈_함수2from mod1 import *# mod2.py
PI = 3.141592
class Math:
def solv(self, r):
return PI * (r ** 2)
def add(a, b):
return a+b
# 클래스, 함수, 변수를 모두 포함
# mod2 사용
import mod2
print(mod2.PI) # 3.141592
a = mod2.Math()
print(a.solv(2)) # 12.566368
print(mod2.add(mod2.PI, 4.4)) # 7.541592
# mod1.py
def add(a, b):
return a+b
def sub(a, b):
return a-b
print(add(1, 4))
print(sub(4, 2))
if __name__ == "__main__":를 사용 시 __name__ == "__main__"이 참이 되어 if 문 다음 문장이 수행된다. __name__ == "__main__"이 거짓이 되어 if 문 다음 문장이 수행되지 않는다.__name__ 변수는 파이썬이 내부적으로 사용하는 특별한 변수 이름이다. C:\python mod1.py처럼 직접 mod1.py 파일을 실행할 경우, mod1.py의 __name__ 변수에는 __main__ 값이 저장된다. __name__ 변수에 mod1.py의 모듈 이름인 mod1이 저장된다.import mod1
mod1.__name__ # 'mod1'
sys.pathsys.path.append를 사용해서 sys.path에 디렉터리를 추가하면 추가된 디렉터리에 저장된 파이썬 모듈을 어디서든 불러 사용할 수 있다.sys.path.append("C:/doit/mymod")
C:\doit>set PYTHONPATH=C:\doit\mymod