모듈 ¶
모듈ì�´ëž€? ¶
- 파�� 프로그램 파� 혹� C 확장 파�
- 프로그램(함수, í�´ëž˜ìФ... )ê³¼ ë�°ì�´í„°ë¥¼ ì •ì�˜
- 사용ìž�ê°€ 모듈ì—� ì •ì�˜ë�œ 함수나 변수ì�˜ ì�´ë¦„ì�„ 사용하ë�„ë¡� 허용하는것 ( = ë�¼ì�´ë¸ŒëŸ¬ë¦¬)
모듈ì�„ 왜 ì‚¬ìš©í• ê¹Œ? ¶
- 코드를 재사용 í• ìˆ˜ 있다.
- ëª¨ë“ ê²ƒì�´ 모듈단위로 분리ë�˜ì–´ 있다.
- 별ë�„ì�˜ ì�´ë¦„공간ì�´ 있어서 다른 모듈과 겹치지 않기 때문ì—� ë�…립ì �ì�¸ 작업ì�´ 가능하다.
모듈만들기(간단하게..) ¶
~cpp
c = 2
def add(a, b):
return a+b
def mul(a, b):
return a*b
mymath.py ë�¼ëŠ” 파ì�¼ë¡œ ì €ìž¥í•œë‹¤..
~cpp >>> import mymath >>> dir(mymath) ['__builtins__', '__doc__', '__file__', '__name__', 'add', 'c', 'mul'] >>> mymath <module 'mymath' from 'C:\Python22\mymath.py'> >>> >>> mymath.c 2 >>> mymath.add <function add at 0x00A927E0> >>> mymath.add(3,4) 7 >>> mymath.mul(4,6) 24
ì�´ë¦„공간 ¶
- ì�´ë¦„공간 = ì�´ë¦„ì�´ ì €ìž¥ë�˜ëŠ” 공간
- �격변수 = ddd.sss 같� �름공간� 명확히 나타나 있는 변수.
- 무�격변수 = ktf 같� 공간� 명확하지 않� 변수.
ì „ì—공간, ì§€ì—공간 ¶
globals(), locals()
~cpp
a = 1
b = 2
def f():
localx = 10
localy = 20
print 'ì „ì—변수:', globals()
print 'ì§€ì—변수:', locals()
f()
print '모듈 수준ì—�서ì�˜ ì „ì—변수:', globals()
print '모듈 수준ì—�서ì�˜ ì§€ì—변수:', locals()
ì¶œë ¥ê°’
~cpp ì „ì—변수 a,b ì§€ì—변수 localx,localy 아래 ë‘�개는.. a,b,f()
모듈 공간ì�˜ ì�´ë¦„ 알아보기 ¶
ì–´ë– í•œ ì†�성ì�„ ì •ì�˜í•˜ê³ 있는가...
~cpp >>> import string >>> dir(string) ['_StringTypes', '__builtins__', '__doc__', '__file__', '__name__', '_float', '_idmap', '_idmapL', '_int', '_long', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
모듈ì�˜ ì�´ë¦„ 공간얻기 ¶
~cpp 너무길다..ì§�ì ‘ë³´ì—¬ì£¼ìž�..!! import string string.__dict__
ì�´ë¦„공간ì�„ 갖는것들 ¶
- 모듈, 함수, �래스 등..
- 외부ì—�서 ê°’ ì„¤ì •ì�´ 가능함..
~cpp
>>> string.b
Traceback (most recent call last):
File "<pyshell#17>", line 1, in ?
string.b
AttributeError: 'module' object has no attribute 'b'
>>> string.b=2
>>> string.b
2
모듈 import 하기 ¶
- import 모듈명 (부르기..)
- from 모듈명 import �름 (�름.. 사용)
- from 모듈명 import* (모�.. 사용)
- import 모듈명 as 새�름 (바꾸기..)
- from 모듈명 import �름 as 새�름 (바꾸기.. )










