[python] 모듈

박민주·2021년 6월 2일
0

파이썬

목록 보기
13/16

모듈이란?

프로그램의 기능을 독립적인 부품으로 분리한 것으로,
필요할 때마다 이러한 부품의 모듈을 적재적소에 추가하며 사용할 수 있어서
코드의 재사용, 용이한 유지보수, 단순한 인터페이스 등의 장점이 있다.

>> Themapark_module.py

# 성인 가격
def price(people):
    print("{0}명 가격은 {1}원 입니다.".format(people, people * 15000))

# 조조할인 가격
def price_morning(people):
    print("{0}명 조조할인 가격은 {1}원 입니다.".format(people, people * 10000))

# 군인할인 가격
def price_solider(people):
    print("{0}명 군인 할인 가격은 {1}원 입니다.".format(people, people * 7000))
    
# 연장자 할인 가격
def price_elderly(people):
    print("{0}명 연장자 할인 가격은 {1}원 입니다.".format(people, people * 5000))

module을 import하는 여러 방법

>> prac.py

# 1. 기본 import
import Themapark_module
Themapark_module.price(3) # 3명이서 테마파크 갔을 때 가격
Themapark_module.price_morning(4) # 4명이서 조조 할인 테마파크 갔을 때
Themapark_module.price_solider(5) # 5명의 군인이 테마파크 갔을 때
Themapark_module.price_elderly(2) # 2명의 연장자가 테마파크 갔을 때

# 2. Themapark_module을 변수에 넣어 import
import Themapark_module as tm
tm.price(3)
tm.price_morning(4)
tm.price_solider(5)
tm.price_elderly(2)

# 3. Themapark_module 파일을 전부 import
from Themapark_module import *
price(3)
price_morning(4)
price_solider(5)
price_elderly(2)

# 4. 필요한 요소들만 import
from Themapark_module import price, price_morning
price(3)
price_morning(4)
price_solider(5) # error

모듈 외부/내부 호출

>>banana.py

class BananaPackage:
    def detail(self):
        print("[바나나] 1송이 3000원 ")

# banana 모듈 직접 실행

if __name__ == "__main__":
    print("banana모듈을 내부에서 직접 실행")
    get_to = BananaPackage()
    get_to.detail()

else:
    print("외부에서 모듈 호출")
# 외부에서 banana 모듈 호출

>>prac.py

from fruits.banana import BananaPackage
get_to = BananaPackage()
get_to.detail()
profile
개발공부

0개의 댓글