본문 바로가기

Backend/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))

# practice.py
import theater_module
theater_module.price(3)
theater_module.price_morning(4)
theater_module.price_soldier(5)

import theater_module as mv  # 별명으로 사용
mv.price(3)
mv.price_morning(4)
mv.price_soldier(5)

from theater_module import * # 모든 함수 가져오기 
price(3)
price_morning(4)
price_soldier(5)

from theater_module import price, price_morning 
price(5)
price_morning(6)
price_soldier(7)  # 쓸수없음

from theater_module import price_soldier as price
price(5)

 패키지 : 하나의 디렉토리에 여러 모듈 파일을 가져 놓은 것

#__init__.py
__all__ = ["vietnam", "thailand"]

# thailand.py
class ThailandPackage:
    def detail(self):
        print("[태국 패키지 3박 5일] 방콕, 파타야 여행(야시장 투어) 50만원")

# vietnam.py
class VietnamPackage:
    def detail(self):
        print("[베트남 패키지 3박 5일] 다낭 효도 여행 60만원")

# practice.py
import travel.thailand     # class나 package는 바로 import할 수 없음.
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()

from travel.thailand import ThailandPackage  # class나 package를 바로 import할 수 있음.
trip_to = ThailandPackage()
trip_to.detail()

from travel import vietnam
trip_to = vietnam.VietnamPackage()
trip_to.detail()

# __all__
from travel import *
trip_to = vietnam.VietnamPackage()
trip_to = thailand.ThailandPackage()
trip_to.detail()

모듈 직접 실행

# thailand.py

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

패키지, 모듈 위치

from travel import *

print(inspect.getfile(thailand))

외장함수 (glob, os, time, datetime, timedelta)

# glob : 경로 내의 폴더/파일 목록 조회
import glob
print(glob.glob("*.py"))  # 확장자가 py인 모든 파일

# os : 운영체제에서 제공하는 기본 기능
import os
print(os.getcwd())

folder = "sample.dir"

if os.path.exists(folder):  # 폴더 삭제
    print("이미 존재하는 폴더입니다.")
    os.rmdir(folder)
    print(folder, "폴더를 삭제하였습니다.")
else:
    os.makedirs(folder)  # 폴더 생성
    print(folder, "폴더를 생성하였습니다.")

# 시간 
import time
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S"))

# 오늘 날짜
import datetime
print("오늘 날짜는 ", datetime.date.today())

# timedelta : 두 날짜 사이의 간격
today = datetime.date.today()
td = datetime.timedelta(days=100)
print("우리가 만난지 100일은", today + td)

'Backend > Python' 카테고리의 다른 글

웹크롤링 2.주식현재가 엑셀로 저장하기  (0) 2022.03.02
웹크롤링 1. 뉴스제목+링크 가져오기  (0) 2022.03.02
예외처리  (0) 2022.02.06
클래스  (0) 2022.02.05
입출력  (0) 2022.02.01