shapes 패키지에는 __init__.py 파일과 함께 아래와 같은 모듈이 있다.
shapes/area.py
PI = 3.14
# 원의 넓이
def circle(radius):
return PI * radius ** 2
# 정사각형 넓이
def square(length):
return length * length
shapes/volume.py
PI = 3.14
# 구의 부피
def sphere(radius):
return (4/3) * PI * radius ** 3
# 정육면체 부피
def cube(length):
return length * length * length
import shapes.volume
print(shapes.volume.cube(3))
# 27
import shapes
print(shapes.volume.cube(3))
# 오류
from shapes import volume
print(volume.cube(3))
# 27
from shapes.volume import cube
print(cube(3))
# 27
as 키워드를 써서 이름을 바꿔줄 수 있다.
import shapes.volume as vol
print(vol.cube(3))
# 27
shapes/__init__.py
from shapes import area, volume
run.py
import shapes
print(shape.area.circle(2))
print(shape.volume.sphere(2))
# 12.56
# 33.4933333333
package. 으로 접근해야 함shapes/__init__.py
from shapes.area import circle, square
run.py
import shapes
print(shape.circle(2))
print(shape.square(3))
# 12.56
# 9
shapes/__init__.py
PI = 3.14
shapes/area.py
from shapes import PI
def circle(radius):
...
shapes/volume.py
from shapes import PI
def sphere(radius):
...
run.py
# PI 직접 import
from shapes import PI
# 패키지 import 후 shapes. 로 접근
import shapes
shapes.PI
import * 를 했을 때 import 대상에서 어떤 것들을 가져와야 하는지 정해 주는 변수from shapes.area import * 를 했을 때 모든 내용이 import 되지 않고 circle, square 함수만 import 됨shapes/area.py
__all__ = ['circle', 'square']
PI = 3.14
# 원의 넓이
def circle(radius):
return PI * radius ** 2
# 정사각형 넓이
def square(length):
return length * length
from shapes import * 를 했을 때 area, volume 모듈만 import 됨shapes.__init__.py
__all__ = ['area', 'volume']
mymath/
shapes/
__init__.py
area.py
volume.py
stats/
__init__.py
average.py
spread.py
run.py
# 패키지 import
import mymath
# 서브패키지 import
import mymath.shapes
# 모듈 import
import mymath.shapes.area
# 모듈 안에 있는 변수나 함수는 이 방식으로 import 불가능
import mymath.shapes.area.circle
# 오류
run.py
# 패키지 안에 있는 패키지 import
from mymath import shapes
# 패키지 안에 있는 모듈 import
from mymath.shapes import area
# 모듈 안에 있는 함수 import
from mymath.shapes.area import circle
# import 뒤에는 . 을 쓸 수 없음
from mymath import shapes.area
# 오류
mymath/shapes/__init__.py
# 절대 경로 임포트
from mymath.shapes import area, volume
# 상대 경로 임포트
from . import area, volume
mymath/stats/__init__.py
# 절대 경로 임포트
from mymath.stats.average import *
from mymath.stats.spread import *
# 상대 경로 임포트
from .average import *
from .spread import *
mymath/shapes/area.py
# 절대 경로 임포트
from mymath.stats.average import data_mean
# 상대 경로 임포트
from ..stats.average import data_mean
위 경우 상대 경로를 봐서는 average 모듈이 정확히 어디 있는지, 패키지 구조가 어떻게 되는지 파악하기가 힘듦, 상대 경로가 복잡해지는 경우에는 그냥 절대 경로를 쓰는 것이 좋다.