파이썬3 바이블 - 제12장 연습문제

프리렉 - FREELEC

http://freelec.co.kr/book/catalogue_view.asp?UID=134

이강성저

1.

자격변수는 변수의 이름공간이 주어지는 표현이다. 이름 공간의 구분은 점(.)으로 하며 연속으로 연결될 수 있다. 예를 들어 X.a에서 변수 a의 이름공간은 X이다.

무자격 변수는 찾고자 하는 변수가 LEGB 영역 안에 있을 때 먼저 발견되는 이름을 사용한다. 하지만 다른 이름 공간에 있을 때에는 자격변수 형식으로 표현해야 한다.

import math

math.sin(0.0)  # sin 함수는 자격 변수로 표현해야 한다.

###################
class A:
    def __init__(self):
        self.a = 10     # self 공간 안에서의 변수 a
        a = 20          # __init__ 안에서의 지역변수.

    def f(self):
        #print(a)        # ???
        print(self.a)    # self 공간 안에서의 변수 a. 자격 변수로 표현해야 한다.

2.

import string 은 string 모듈(이름공간)을 가져온다. 현재 이름 공간에 등록되는 이름은 string 뿐이다.

from string import * 는 모듈 string안에 정의된 이름들을 현재 이름 공간에 모두 가져온다.

3.

이름 공간은 일반적으로 사전으로 표현된다.

In [1]:
# 현재 모듈의 전역 이름 공간을 얻는 방법

# 방법 1
ns1 = globals()

# 방법 2
import sys
ns2 = sys.modules[__name__].__dict__ 
In [2]:
# 가져오기 한 모듈의 이름 공간을 얻는 방법

import math

math.__dict__
Out[2]:
{'__doc__': 'This module is always available.  It provides access to the\nmathematical functions defined by the C standard.',
 '__file__': '/usr/local/lib/python3.3/lib-dynload/math.cpython-33m.so',
 '__loader__': <_frozen_importlib.ExtensionFileLoader at 0x7fb9acc96ad0>,
 '__name__': 'math',
 '__package__': '',
 'acos': <function math.acos>,
 'acosh': <function math.acosh>,
 'asin': <function math.asin>,
 'asinh': <function math.asinh>,
 'atan': <function math.atan>,
 'atan2': <function math.atan2>,
 'atanh': <function math.atanh>,
 'ceil': <function math.ceil>,
 'copysign': <function math.copysign>,
 'cos': <function math.cos>,
 'cosh': <function math.cosh>,
 'degrees': <function math.degrees>,
 'e': 2.718281828459045,
 'erf': <function math.erf>,
 'erfc': <function math.erfc>,
 'exp': <function math.exp>,
 'expm1': <function math.expm1>,
 'fabs': <function math.fabs>,
 'factorial': <function math.factorial>,
 'floor': <function math.floor>,
 'fmod': <function math.fmod>,
 'frexp': <function math.frexp>,
 'fsum': <function math.fsum>,
 'gamma': <function math.gamma>,
 'hypot': <function math.hypot>,
 'isfinite': <function math.isfinite>,
 'isinf': <function math.isinf>,
 'isnan': <function math.isnan>,
 'ldexp': <function math.ldexp>,
 'lgamma': <function math.lgamma>,
 'log': <function math.log>,
 'log10': <function math.log10>,
 'log1p': <function math.log1p>,
 'log2': <function math.log2>,
 'modf': <function math.modf>,
 'pi': 3.141592653589793,
 'pow': <function math.pow>,
 'radians': <function math.radians>,
 'sin': <function math.sin>,
 'sinh': <function math.sinh>,
 'sqrt': <function math.sqrt>,
 'tan': <function math.tan>,
 'tanh': <function math.tanh>,
 'trunc': <function math.trunc>}

4.

In [3]:
!mkdir mypythonlib
mkdir: `mypythonlib' 디렉토리를 만들 수 없습니다: 파일이 있습니다

In [4]:
%%writefile mypythonlib/spam.py
print('test')
Overwriting mypythonlib/spam.py

In [5]:
import spam  # 모듈 경로를 찾을 수 없다
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-24777a94c001> in <module>()
----> 1 import spam  # 모듈 경로를 찾을 수 없다

ImportError: No module named 'spam'
In [15]:
# 해결방법1 - 모듈이 저장된 경로를 동적으로 추가해준다.
import sys
sys.path.append('mypythonlib')

import spam
test

In [16]:
# 해결방법2 - 셸 변수 PYTHONPATH에 경로 추가
!export PYTHONPATH=mypythonlib:$PYTHONPATH
In [17]:
import spam

5.

동적으로 모듈을 가져오는 방법은 __import__ 함수를 이용한다.

In [7]:
modulename = 'math'
In [8]:
__import__(modulename)
Out[8]:
<module 'math' from '/usr/local/lib/python3.3/lib-dynload/math.cpython-33m.so'>
In [9]:
os = __import__('os')

os.path.join('a', 'b')
Out[9]:
'a/b'
In [10]:
path = __import__('os.path', fromlist=['join'])
path.join('a', 'b')
Out[10]:
'a/b'

6.

In [11]:
import sys

're' in sys.modules
Out[11]:
True

7.

In [12]:
math
Out[12]:
<module 'math' from '/usr/local/lib/python3.3/lib-dynload/math.cpython-33m.so'>
In [13]:
import imp

imp.reload(math)   # 강제 재적재
Out[13]:
<module 'math' from '/usr/local/lib/python3.3/lib-dynload/math.cpython-33m.so'>

8.

현재 디렉토리가 Speech 부모 라면 다음과 같은 가져오기는 잘 동작한다.

하지만 현재 디렉토리가 Speech/Recognition이라면 다음과 같은 실행 결과가 나온다.

$ python3.3 NN.py 
Traceback (most recent call last):
  File "NN.py", line 1, in <module>
    from . import DTW
SystemError: Parent module '' not loaded, cannot perform relative import
gslee@usan:Recognition$ python3.3 -c 'import NN'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "./NN.py", line 1, in <module>
    from . import DTW
SystemError: Parent module '' not loaded, cannot perform relative import

모듈의 실행은 패키지 바깥쪽에서 해야 한다. 이름이 '__main__'인 모듈이 상대 가져오기를 실행할 수는 없다. 상대 가져오기는 패키지 안에서만 동작한다.

9.

In [13]: