game/
__init__.py
sound/
__init__.py
echo.py
graphic/
__init__.py
screen.py
render.py
play/
__init__.py
run.py
test.py
def echo_test():
print("echo")
def reder_test():
print("render")
C:\> set PYTHONPATH=C:/doit
C:\> python
Python 3.7.3 (v3.7.3:ef4e...
>>>
import하여 실행하는 방법
>>> import game.sound.echo
>>> game.sound.echo.echo_test()
echo
from...import하여 실행하는 방법
>>> from game.sound import echo
>>> echo.echo_test()
echo
모듈 안의 함수를 직접 import하여 실행하는 방법
>>> from game.sound.echo import echo_test
>>> echo_test()
echo
하지만 다음과 같이 사용하는 것은 불가능
>>> import game
>>> game.soud.echo.echo_test()
Traceback(most recent call last):
File "<stdin>", line 1, in <module>
AttributeError:'module' object has no attribute 'sound'
imprt game을 수행 하면 game 디렉터리의 모듈 또는 game 디렉터리의 __init__.py에 정의한 것만 참조할 수 있다.
또한 다음과 같이 사용하는 것도 불가능
>>> import game.sound.echo.eho_test
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named echo_test
도트(.) 연산자를 사용해서 import할 때 가장 마지막 항목은 반드시 모듈 또는 패키지여야한다.
__init__.py 파일은 해당 디렉터리가 패키지의 일부임을 알려주는 역할을 한다. __init__.py 파일이 없는경우 패키지로 인식하지 않는다.
>>> from game.sound.import*
>>> echo.echo_test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError:name 'echo' is not defined
위와 같이 특정 디렉터리의 모듈을 *을 사용하여 import할 때에는 아래와 같이 해당 디렉터리의 __init__.py파일에 __all__변수를 설정하고 import 할 수 있는 모듈을 정의해 주어야한다.
# C:/doit/game/sound/\_\_init\_\_.py
\_\_all\_\_ = ['echo']
만약 graphic 디렉터리ㅣ의 render.py 모듈이 sound 디레거리의 echo.py 모듈을 사용하고 싶다면 아래와 같이 수정해볼 수 있다.
#render.py
from game.sound.echo import echo_test
def render_test()
print("render")
echo_test()
또는
#render.py
from ..sound.echo import echo_test
def render_test():
print("render")
echo_test()
.. 와 같은 relative한 접근자는 모듈안에서만 사용해야 한다.