[References]
http://pythonstudy.xyz
모듈(Module)
변수, Class, 함수 등과 같은 여러 Code를 한 곳에 모아놓은 Code의 모음
한 번 만들어 놓으면 계속 사용할 수 있기 때문에 재사용성을 극대화 할 수 있다.
연관성이 높은 것들을 Module 단위로 분리하여 효율성을 높일 수 있다.
Module은 'import'라는 Keyword를 통해 불러올 수 있다.
'dir' Function을 사용하면 그 Module 내에 있는 여러 가지 Data와 Function들을 알아낼 수 있다.
import math
dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
Module 내에 있는 Function을 사용하려면 'Module Name.Function Name'과 같이 사용한다.
import math
print(math.sin(90))
# 0.8939966636005579
print(math.pow(2, 10))
# 1024.0
print(math.pi)
# 3.141592653589793
Module의 정의
(1) Python의 Module은 '.py'로 저장되어 있으며 Python이 설치되어 있는 Directory 내 lib 안에서 찾을 수 있다.
(2) Python에서 Module을 정의한다는 것은 File을 만든다는 의미이다.
(3) 사칙연산을 지원하는 Module 제작 ('arithmetic.py'로 저장)
(만든 파일을 c:\...\python3\lib> 안에 저장)
def plus(a, b):
retrun a + b
def minus(a, b):
retrun a - b
def mul(a, b):
retrun a * b
def div(a, b):
retrun a / b
import arithmetic
dir(arithmetic)
print(arithmetic.plus(1, 2))
# 3
print(arithmetic.mul(300, 400))
# 120000
(4) Module 명을 적지 않고 바로 참조하려면 아래와 같이 import 구문을 사용한다.
# from 'Moduel Name' import 'Attribute'
from arithmetic import plus
print(plus(100, 200))
# 300
(5) Module 명을 적지 않고 모든 Attribute 참조
from 'Moduel Name' import *
from arithmetic import *
print(plus(100, 200))
# 300
print(minus(300, 200))
# 100
print(div(500, 2))
# 250.0