나를 기록하다
article thumbnail
Published 2023. 3. 23. 17:50
[Python] 모듈 기타/Python
반응형

 

모듈

# 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))

 

실행파일

1) 일반 호출

# 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원입니다.

 

2) 별칭을 지어 짧게 호출

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

 

3) from ~ import * 이용

from theater_module import *
# from random import * 과 같은 구조
price(3)
price_morning(4)
price_soldier(5)

 

4) 필요한 함수만 import

from theater_module import price, price_morning
price(3)
price_morning(4)
# price_soldier(5) -> import 하지 않았기에 사용 불가
# 필요한 함수만 import 해서 별칭 사용 가능
from theater_module import price_soldier as price
price(5)

 

 

importfrom import

importfrom import는 둘 다 다른 모듈에서 코드를 가져오는 데 사용되는 파이썬의 키워드입니다.

import는 전체 모듈을 가져오는 데 사용되며 모듈 이름을 지정해야 합니다. 이후 코드에서 모듈 이름을 사용하여 해당 모듈의 기능 및 변수에 액세스할 수 있습니다. 예를 들어, "import math"는 math 모듈을 가져와서 해당 모듈의 함수를 호출할 수 있습니다.

반면에 from import는 특정 모듈에서 특정 함수나 변수를 가져오는 데 사용됩니다. 이 키워드를 사용하면 모듈 이름을 지정하고 가져올 함수나 변수 이름을 지정할 수 있습니다.

예를 들어, "from math import sqrt"는 math 모듈에서 sqrt 함수만을 가져와서 코드에서 바로 사용할 수 있게 됩니다.

따라서, import는 전체 모듈을 가져오고, from import는 특정 함수나 변수를 가져온다는 것이 두 키워드의 차이점입니다.

 

예시

import travel.thailand # 클래스나 함수는 import를 할 수 없음
trip_to =travel.thailand.ThailandPackage()
trip_to.detail()
from travel.thailand import ThailandPackage
trip_to = ThailandPackage()
trip_to.detail()
from travel import vietnam
trip_to = vietnam.VietnamPackage()
trip_to.detail()
# __init__.py 가 비어있는 상태에서 실행
# 오류 발생
from travel import *
trip_to = vietnam.VietnamPackage()
trip_to.detail()
# __init__.py 에 입력
__all__ = ["vietnam"]
# practice.py 에서 구문 실행
from travel import *
trip_to = vietnam.VietnamPackage()
trip_to.detail()

 

 

반응형
profile

나를 기록하다

@prao

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...