python

모듈과 패키지.py

몽자비루 2023. 3. 20. 02:14
## 모듈
# 필요한 기능끼리 부품처럼 잘 만들어진 파일을 의미함.
# 유지보수 및 코드의 재사용이 편리해짐.

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

# theater_module의 내용을 mv로 호출할 수 있음
import theater_module as mv
mv.price(3)
mv.price_morning(4)
mv.price_soldier(5)

# from random import *
# theater_module을 작성할 필요없이 모든것을 import하겠다는 의미.
from theater_module import *
price(3)
price_morning(4)
price_soldier(5)

# theater_module 에서 필요한 몇몇개의 함수만 쓰겠다는 의미.
# price_soldier 을 호출할 수 없다.
from theater_module import price, price_morning
price(3)
price_morning(4)
try:
    price_soldier(5)
except NameError:
    print("해당 함수는 정의되지 않았습니다.")

# price_soldier 에 price라는 별명을 붙임.
from theater_module import price_soldier as price
# price_soldier이 호출됨
price(3)

theater_module.py 모듈

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

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

# 군인 할인 가격
def price_soldier(people):
    print("{}명 군인할인 가격은 {}원 입니다.".format(people, people*4000))
  • 모듈이란 필요한 기능끼리 부품처럼 모인, 잘 만들어진 파일을 의미한다.
  • 유지보수 및 코드의 재사용이 편리해짐.
  • 모듈을 호출할 수 있는 방법은 여러가지가 있다.
  • 모듈 내 모든 함수/기능을 호출하는 방법
    ㄴ import 모듈명 : 모듈명.함수 로 모듈 내 함수 기능 호출 가능.
    ㄴ import 모듈명 as 별명 : 모듈에게 별명을 만들어주는 것으로,
                                               별명.함수 로 모듈 내 함수 기능 호출 가능.
    ㄴ from 모듈명 import * : 함수 로 모듈 내 함수 기능 호출 가능.
  • 모듈 내 일부 함수/기능을 호출하는 방법
    ㄴ from 모듈명 import 함수명1, 함수명2 : 모듈 내 함수1, 함수2 만 호출 가능.
    ㄴ from 모듈명 import 함수명1 as 별명 : 함수1 을 별명으로 호출 가능.
## 패키지
# 모듈들을 모아놓은 집합을 의미함.
# import ~ 마지막에 반드시모듈이나 패키지가 와야한다.
# 클래스나 함수는 import를 바로 할 수 없음.
# import travel.thailand.ThailandPackge X
import travel.thailand
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()

# from~import 구문에서는 모듈, 패키지, 함수, 클래스 모두  import 가능.
# from 패키지.모듈 import 클래스
from travel.thailand import ThailandPackage
trip_to = ThailandPackage()
trip_to.detail()

# from 패키지 import 모듈.
from travel import vietnam
trip_to = vietnam.VietnamPackage()
trip_to.detail()

travel 패키지

더보기

init.py

__all__ = ["vietnam", "thailand"]

thailand.py

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

## 모듈 직접 설정.
# 패키지/모듈을 만들 때 모듈이 잘 작동되는지 확인해야 함.
# name == main이면, 즉 Thailand.py 에서 코드를 직접 실행했을 때, 
# 해당 문장은 함수호출로 실행하지 않더라도 호출되는 순간 바로 실행된다.
if __name__ == "__main__":
    print("Thailand 모듈을 직접 실행")
    print("이 문장은 모듈을 직접 실행할 때만 실행됩니다.")
    trip_to = ThailandPackage()
    trip_to.detail()
else : 
    print("Thailand 외부에서 모듈 호출")

vietnam.py

class VietnamPackage:
    def detail(self):
        print("[베트남 패키지 3박5일] 다낭 호도여행 60만원")
  • 패키지 : 모듈들을 모아놓은 집합을 의미함.
  • import 로 모듈을 호출하는 경우, 마지막에 반드시 모듈이나 패키지가 와야한다.
    즉, 클래스나 함수는 바로 import 할 수 없다.
  • from~import 구문에서는 모듈, 패키지, 함수, 클래스 모두 import 가능하다.
## __all__
# travel 모듈안의 모든것을 import하겠다는 의미.
# 실제로는 개발자가 문법안에서 공개범위를 설정해야 함.
# 모듈 안의 __init__ 에 `__all__ = ["vietnam", "thailand"]`
from travel import *
trip_to = vietnam.VietnamPackage()
trip_to.detail()

trip_to = thailand.ThailandPackage()
trip_to.detail()
  • from travel import * 은 travel 모듈 안의 모든것을 import하겠다는 의미이다.
  • 하지만 실제로는 개발자가 문법 안에 공개범위를 설정해야 한다.
  • __init__ 을 살펴보면 __all__ = ["vietnam", "thailand"] 이 있는데,
    travel 모듈안의 vietnam과 thailand 를 import할 수 있도록 하겠다는 의미.
## 모듈 직접 설정.
# 패키지/모듈을 만들 때 모듈이 잘 작동되는지 확인해야 함.
# name == main이면, 즉 Thailand.py 에서 코드를 직접 실행했을 때, 
# 해당 문장은 함수호출로 실행하지 않더라도 호출되는 순간 바로 실행된다.
if __name__ == "__main__":
    print("Thailand 모듈을 직접 실행")
    print("이 문장은 모듈을 직접 실행할 때만 실행됩니다.")
    trip_to = ThailandPackage()
    trip_to.detail()
else : 
    print("Thailand 외부에서 모듈 호출")

thailand.py 의 `## 모듈 직접 실행` 부분 참고

  • __name__ == "__main__" 란, 해당 파일 자체를 실행한 경우를 의미한다.
  • 검색결과에 따르면, 파일 안에서 함수를 실행시키면,__name__ 변수에 담기는 것은
    파일, 혹은 모듈의 이름이 아니고, __main__ 이라는 값이 됨.
## 패키지, 모듈 위치
# 그동안 같은 경로에 있는 패키지 모듈 사용해왔음.
# 위치를 모르는 패키지 모듈이 어디에 있는지 확인할 방법
import inspect
import random
print(inspect.getfile(random))
print(inspect.getfile(thailand))
  • inspect.getfile(모듈명) 을 통해 모듈이 어디에 있는지 확인함
## pip installl
# 패키지를 설치할 수 있다.
# pip install 패키지명 : 패키지를 설치할 수 있음.
# pip list : 설치된 패키지 리스트를 받아올 수 있음.
# pip show 패키지명 : 패키지에 대한 정보를 보여줌.
# pip install --upgrade 패키지명 : 해당패키지를 업그레이드 진행함.
# pip uninstall  패키지명 : 패키지 설치 삭제함.
  • pip install 패키지명 : 패키지를 설치할 수 있음.
  • pip list : 설치된 패키지 리스트를 받아올 수 있음.
  • pip show 패키지명 : 패키지에 대한 정보를 보여줌.
  • pip install --upgrade 패키지명 : 해당 패키지 업그레이드 진행함.
  • pip uninstall 패키지명 : 패키지 설치 삭제함.
## 내장함수
# 따로 import할 필요 없이 바로 사용가능한 함수.
# ex) input, print, ...
# dir : 어떤 객체를 넘겨줬을 때, 그 객체가 어떤 변수와 함수를 가지고 있는지 표시.
import random
print(dir())
# random 모듈 내에서 쓸수 있는 것들을 출력함.
print(dir(random))

list = [1,2,3]
# list 모듈 내에서 쓸수 있는 것들이 출력됨
print(dir(list))

name = "조OO"
# string 에서 사용할 수 있는 것들을 출력함.
print(dir(name))
  • 내장함수 란 따로 import 할 필요없이 사용 가능한 함수.
## 외장함수
# 내장함수와 달리 직접 import하여 사용해야하는 것들
# list of pythono modules 검색 후 확인 가능.

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

# os : 운영체제에서 제공하는 기본기능
import os
# 현재 디렉토리 표시
print(os.getcwd())
folder = "sample_dir"

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

# 현제 디렉토리 내 파일목록을 출력함.
print(os.listdir())

print("--------------import time--------------")
# time : 시간관련 함수
import time
print(time.localtime())
# 원하는 형태로 출력할 수 있음.
print(time.strftime("%Y-%m-%d %H:%M:%S "))

# datetime
import datetime
print("오늘 날짜는 :", datetime.date.today())
td = datetime.timedelta(days=100) # 100일을 저장함.
print("오늘 기준 100일 뒤는", datetime.date.today() + td)
print("오늘 기준 100일 전은", datetime.date.today() - td)
  • 외장함수 : 내장함수와 달리 직접 import하여 사용해야하는 것들
  • 구글에 list of python modules 검색 후 확인할 수 있다.
  • glob : 경로 내 폴더/파일 목록 조회 (윈도우 dir)
    ㄴ glob.glob("*확장자") 로 특정 확장자 파일을 찾을 수 있음.
  • os : 운영체제에서 제공하는 기본기능을 함수로 쓸수있음.
    ㄴ os.getcwd() = 현재 디렉토리 표시
    ㄴ os.path.exist(forder) = forder 이 있는지 확인
    ㄴ os.makedirs(forder) = forder을 생성
    ㄴ os.rmdir(forder) = forder을 삭제
    ㄴ os.listdir() = 현재 디렉토리 내 파일목록을 출력.
  • time : 시간과 관련된 함수.
    ㄴ time.localtime() = 현재 시간을 출력함.
    ㄴ time.strftime() = 시간을 원하는 형태로 출력함.
  • datetime : 날짜와 관련된 함수.
    ㄴ datetime.date.today() = 오늘 날짜 출력
    ㄴ datetime.timedelta(days=n) = n만큼의 날짜를 의미함.
## 퀴즈
'''
프로젝트 내 나만의 시그니처를 남기는 모듈을 만들기.
'''
import byme
byme.sign()
  • byme.py
def sign():
    print("이 프로그램은 `조OO` 에 의해 만들어졌습니다.")
    print("유튜브 : <http://youtube.com>")
    print("이메일 : id@domain.com")
  • byme.py 모듈을 만든 뒤 import byme를 통해 호출.
    ㄴ byme.sign()을 통해 byme모듈의 sign 함수를 호출함.
  • 터미널에 cls를 입력해서 터미널 내용을 clear할수 있음.