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.0269 sec