ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [python] 모듈
    python 2025. 6. 2. 11:24

    모듈

    Python에서 모듈(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))

     

    # practice.py 에서 확인

    import theater_module
    theater_module.price(3) # 3명이서 영화 보러 갔을 때 가격
    theater_module.price_morning(4) # 4명이서 조조 할인 영화 보러 갔을 때 가격
    theater_module.price_soldier(5) # 5명의 군인이 영화보러 갔을 때 가격

     

    3명 가격은 30000원 입니다.
    4명 조조 할인 가격은 24000원 입니다.
    5명 군인 할인 가격은 20000원 입니다.

     

    import theater_module as mv
    mv.price(3)
    mv.price_morning(4)
    mv.price_soldier(5)

     

    모듈 이름(theater_module)이 길 때, 별칭(mv)을 만들어서 사용할 수도 있다.

     

    3명 가격은 30000원 입니다.
    4명 조조 할인 가격은 24000원 입니다.
    5명 군인 할인 가격은 20000원 입니다.

     

    from theater_module import *
    price(3)
    price_morning(4)
    price_soldier(5)

     

    3명 가격은 30000원 입니다.
    4명 조조 할인 가격은 24000원 입니다.
    5명 군인 할인 가격은 20000원 입니다.

     

    from theater_module import price, price_morning
    price(5)
    price_morning(6)
    price_soldier(7)

     

    theater_module에서 price와 price_morning만 가져오므로, price_soldier는 쓸 수 없다.

     

    Traceback (most recent call last):
      File "c:\Users\~~~\practice.py", line 14, in <module>
        price_soldier(7)
        ^^^^^^^^^^^^^
    NameError: name 'price_soldier' is not defined

     

    from theater_module import price_soldier as price
    price(5)

     

    5명 군인 할인 가격은 20000원 입니다.

     

    'python' 카테고리의 다른 글

    [python] __all__  (1) 2025.06.05
    [python] 패키지  (1) 2025.06.02
    [python] finally  (0) 2025.05.29
    [python] 예외처리  (1) 2025.05.29
    [python] 스타크래프트 프로젝트  (0) 2025.05.29
Designed by Tistory.