모듈은 여러 함수와 클래스들을 하나의 파일에 모아놓은 것을 말합니다. 모듈을 통해 코드를 재사용하거나 관리하기 쉽게 만들 수 있습니다.
모듈을 학습하기 위해서 새로운 파일 theater_module.py
를 만들었습니다.
theater_module.py
안의 코드
# 일반 가격
def price(people):
print("{0}명 가격은 {1}원 입니다.".format(people, people * 10000))
# 조조할인 가격
def price_morning(people):
print("{0}명 조조 할인 가격은 {1}원 입니다.".format(people, people * 6000))
# 군인할인 가격
def price_soldier(people):
print("{0}명 군인 할인 가격은 {1}원 입니다.".format(people, people * 4000))
위 코드는 영화표 가격을 계산하는 세 가지 함수를 포함한 theater_module
을 정의한 코드입니다. 각 함수는 people
의 값에 따라 영화 가격을 계산해 출력해줍니다.
다시 연습할 내용을 입력할 파일로 돌아갑니다.!
저는 practice.py
에서 연습을 하고 있으니, practice.py 파일로 가서 실습을 했습니다.
모듈을 사용할 때, import
키워드를 통해 불러와 다양한 방식으로 활용할 수 있습니다.
import theater_module
theater_module.price(3) # 3명의 영화 가격
theater_module.price_morning(4) # 4명의 조조 할인 가격
theater_module.price_soldier(5) # 5명의 군인 할인 가격
practice.py에서 위 코드를 입력해서 theater_module.py
에서 함수를 불러 올 수 있다.
theater_module.price()
같은 방식으로 모듈 안에 있는 함수에 접근할 수 있다.
모둘명이 theater_module
처럼 길면
import theater_module as mv
mv.price(3)
mv.price_morning(4)
mv.price_soldier(5)
이렇게 as
키워드를 사용해서 짧은 별명을 붙여 더 간결하게 사용할 수 있다.
모듈 안에 있는 모든 함수를 불러와서 사용 할 수있다.
파이썬을 배우면서 from random import *
을 활용했던 것 처럼!
from theater_module import * #theater_module 안의 모든 함수 가져오기
price(3)
price_morning(4)
price_soldier(5)
필요에 따라 선택적으로 가져와 사용할 수도 있다.
from theater_module import price, price_morning
price(3)
price_morning(4)
이렇게 import
뒤에 함수를 나열해서 가져온다.
패키지는 간단히 말해서 여러 모듈을 한 디렉토리에 모아둔 집합이다.
(모듈
⊂ 패키지
라 이해하면 편할듯 하다.)
연습하기 위해서 travel
폴더를 VS Code
에 만들고 안에 thailand.py
, vietnam.py
를 만들었다.
travel/thailand.py
안의 코드
class ThailandPackage:
def detail(self):
print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")
if __name__ == "__main__":
print("Thailand 모듈을 직접 실행")
trip_to = ThailandPackage()
trip_to.detail()
else:
print("Thailand 외부에서 모듈 호출")
travel/vietnam.py
안의 코드
class VietnamPackage:
def detail(self):
print("[베트남 패키지 3박 5일] 다낭 효도 여행 60만원")
여기서 thailand.py
와 vietnam.py
라는 두 개의 모듈을 만들어서, 각각 패키지 클래스를 정의했다.
연습할 파일 practice.py
로 돌아와서
import travel.thailand #travel 패키지 안의 thailand 파일을 호출한다.
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()
패키지 내의 모듈도 import
키워드로 불러와서 사용할 수 있다.
from travel.thailand import ThailandPackage
trip_to = ThailandPackage()
trip_to.detail()
이렇게 필요한 ThailandPackage
클래스만 따로 불러오는 것도 가능하다.
__all__
은 패키지 안에서 어떤 모듈을 공개할지 정하는 설정입니다. __init__.py
파일에 설정해두면 되기에 위에서 연습용으로 만든 travel
폴더에 파일을 만들어 코드를 입력 했습니다.
travel/__init__.py
__all__ = ["vietnam", "thailand"]
이렇게 공개범위를 설정하고
from travel import *
trip_to = vietnam.VietnamPackage()
trip_to.detail()
__all__
에 설정된 모듈들만 *을 사용해서 불러올 수 있다.
모듈은 __name__
값을 통해 직접 실행 여부를 판단할 수 있다.
thailand.py
파일에서
if __name__ == "__main__":
print("Thailand 모듈을 직접 실행")
else:
print("Thailand 외부에서 모듈 호출")
이 코드를 통해 thailand.py
파일이 직접 실행되었는지, 아니면 외부에서 호출되었는지에 따라 다른 동작을 하게 할 수 있다.
모듈과 패키지의 파일 경로를 확일할 때 inspect
모듈을 사용한다.
import inspect
import random
print(inspect.getfile(random))
이 코드를 통해 모듈이 실제로 어디에 있는지 경로를 출력할 수 있다.!
잘 이해가 안되니 코드를 실행하면!
c:\python38\lib\random.py
이렇게 random 함수가 있는 경로를 표시 해 준다.