유튜브 '나도코딩'채널의 파이썬 강좌를 토대로 정리한 내용입니다.
모듈 예시를 들기 위해 theather_module.py이라는 파일이 하나 새로 생성하겠다.
# 일반 가격 def price(people): print("{0}명 가격은 {1}원입니다.". format(people, people * 100000))# 조조 할인 가격 def price_morning(people): print("{0}명 가격은 {1]원입니다.". format(people, people * 6000))# 군인 할인 가격 def price_soldier(people): print("{0}명 가격은 {1]원입니다.". format(people, people * 4000))
theather_module.py 파일에 함수 모듈을 생성하였다.
모듈을 불러와 작업하고 싶은 파일에서 모듈을 불러오는 예시를 한번 살펴보자.
입력
import theather_module theather_module.price(3) theather_module.price_morning(4) theather_module.price_soldier(5)출력
3명 가격은 30000원입니다. 4명의 조조 할인 가격은 24000원입니다. 5명의 군인 할인 가격은 20000원입니다.
import theather_module 모듈을 불러오는 첫번째 방법이다.
모듈의 이름을 임의로 변경하여 원하는 이름으로 쓸 수 있다. 다음 예시를 살펴보자.
import theather_module as mv mv.price(3) mv.price_morning(4) mv.price_soldier(5)
임의 변경한 모듈 이름을 사용하여도 위와 똑같은 결과값을 확인할 수 있다.
모듈을 불러오는 두번째 방법을 살펴보자.
from theather_module import * price(3) price_morning(4) price_soldier(5)
모듈을 불러오는 두번째 방법은 from theather_module import *이다.
두번째 방법으로 모듈을 불러오면 모듈 이름 없이 함수 이름만 쓰면 사용 가능하다.
from theather_module import price, price_morning price(3) price_morning(4)
만약 불러올 함수를 지정해놓고 지정하지 않은 함수를 불러올려고 하면 NameError: name 'price_soldier' is not defined NameError```가 발생한다.
입력
from theather_module import price_soldier as price price(10)출력
10명의 군인 할인 가격은 40000원입니다.
모듈에서 불러온 함수의 이름을 다른 함수의 이름과 동일하게 변경하여도 불러온 함수가 사용된다.