U E D R , A S I H C RSS

2학기파�선스터디/모듈

모듈


모듈�란?

  • 파ì�´ì�¬ 프로그램 파ì�¼ 혹ì�€ 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 새ì�´ë¦„ (바꾸기.. )

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:22:13
Processing time 0.0235 sec