[Tools]/Python 뿌시기

[Python 문법 8.1] - 모듈, 패키지, _all_, 패키지/모듈 위치

pjw250 2024. 9. 26. 23:24

11-6 pip install, 내장함수, 외장함수는 [Python 문법 8.2] 에서 계속..

 

### 모듈 생성 (Theater_module.py)

# 일반 가격
def price(people):
    print('{0}명 가격은 {1}원 입니다.'.format(people, people*10000))

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

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

### 모듈 사용 (Theater_module.py)

import Theater_module
Theater_module.price(3) # 3 명 영화 가격
Theater_module.price_moring(4) # 4 명 조조 영화 가격
Theater_module.price_soldier(5) # 5 명 군인 영화 가격

import Theater_module as mv
mv.price(3) # 3 명 영화 가격
mv.price_moring(4) # 4 명 조조 영화 가격
mv.price_soldier(5) # 5 명 군인 영화 가격

from Theater_module import * # 모듈의 모든 것을 사용하겠다.
price(3)
price_moring(4)
price_soldier(5)

from Theater_module import price, price_moring # 모듈안에 특정 함수만 불러오기
price(3)
price_moring(4)
price_soldier(5) # 오류 발생

from Theater_module import price_soldier as ps # price_soldier 를 ps로 받기
ps(5)

### 패키지와 모듈 [__init__.py, thailand.py, vietnam.py]


import travel.thailand # 패키지(folder) 안에 모듈(.py)
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()

from travel.thailand import ThailandPackage
trip_to = ThailandPackage()
trip_to.detail()

from travel import thailand
trip_to = thailand.ThailandPackage()
trip_to.detail()

from travel import *
trip_to = thailand.ThailandPackage()
trip_to.detail() # 오류 발생
# __init__.py 에 __all__ 에 thailand 추가하여 해결 (공개한다)

### 패키지, 모듈 위치 찾기

import inspect
import random
print(inspect.getfile(random))
print(inspect.getfile(thailand))

 

Travel 패키지(폴더) 안의 모듈(.py)

 

### Travel 폴더안의 __init__.py 내용

__all__ = ['thailand']

 

### Travel 폴더안의 thailand.py 내용

class ThailandPackage:
    def detail(self):
        print('[태국 패키지 3박 5일] 방콕, 파나야 여행 50 만원 ')

if __name__ == '__main__':
    print('Thailand 모듈을 직접 실행')
    print('이 문장은 모듈을 직접 실행할 때만 실행됩니다.')
    trip_to = ThailandPackage()
    trip_to.detail()
else:
    print('Thailand 외부에서 모듈 호출')

 

### Travel 폴더안의 veitnam.py 내용

class VietnamPackage:
    def detail(self):
        print('[배트남 패키지 3박 5일] 다낭 효도 여행 60 만원 ')

 

* 출처 나도코딩 [파이썬 코딩 무료 강의 (기본편)]

파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩] (youtube.com)