[Python응용] 7. 파이썬의 모듈 소개와 직접모듈 작성하기
파이썬 모듈(Library)의 이해
모듈의 정의
- 여러 코드를 묶어 다른곳에서 재사용 할 수 있는 코드의 모음
내장모듈
- 파이썬에서 기본적으로 제공되는 모듈
- 다양한 모듈을 제공
- 문자열(string), 날짜(date), 시간(time), 수학(math), 랜덤(random), 파일(file), sqlite3, os, sys, xml, http 등 약 200개 정도의 다양한 모듈들이 제공됨
import math
math.log(100)
4.605170185988092
math.pi
3.141592653589793
dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
사용자 정의 모듈
- 파이썬에서 기본적으로 제공되는 모듈 외 사용자가 직접 작성한 모듈
- 필요시, 모듈 작성 및 제공 가능
- 내가 만든 모듈을 다른 개발자에게 제공하거나 다른 개발자가 만든 모듈을 제공받을 수 있음
## 함수를 구현한 사용자 정의 모듈을 {python 설치 폴더}\lib에 복사
from functools import *
def intersect(*ar):
return reduce(__intersectSC,ar)
def __intersectSC(listX, listY):
setList = []
for x in listX:
if x in listY:
setList.append(x)
return setList
def difference(*ar):
setList = []
intersectSet = intersect(*ar)
unionSet = union(*ar)
for x in unionSet:
if not x in intersectSet:
setList.append(x)
return setList
def union(*ar):
setList = []
for item in ar:
for x in item:
if not x in setList:
setList.append(x)
return setList
import simpleset
dir(simpleset)
['WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', '__builtins__', '__cached__', '__doc__', '__file__', '__intersectSC', '__loader__', '__name__', '__package__', '__spec__', 'cmp_to_key', 'difference', 'intersect', 'lru_cache', 'partial', 'partialmethod', 'reduce', 'singledispatch', 'singledispatchmethod', 'total_ordering', 'union', 'update_wrapper', 'wraps']
setA = [1, 2, 3]
setB = [3, 4, 5]
simpleset.union(setA, setB)
[1, 2, 3, 4, 5]