[Python] 모듈과 패키지

2 minute read

[Python] 모듈과 패키지Permalink

Inflearn StudyPermalink


링크: https://www.inflearn.com/

  • 인프런에서 “파이썬 무료 강의 (기본편) - 6시간 뒤면 나도 개발자” 강의를 들으며 혼자 공부한 내용입니다.

모듈Permalink


: 파이썬 코드를 논리적으로 묶어서 관리하고 사용할 수 있도록 하는 것

  • 하나의 파이썬.py 파일이 하나의 모듈이 됩니다.
# theather_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))
import theater_module # 파일명만 쓰면 된다.
theater_module.price(3) # 3명이서 영화 보러 갔을 때 가격
theater_module.price_morning(4) # 4명이서 조조할인 영화 보러 갔을 때 가격
theater_module.price_soldier(5) # 5명의 군인이 영화 보러 갔을 때의 가격
  • import 모듈
    • 모듈 안에 있는 함수들을 사용할 수 있습니다.
import theater_module as mv # as 뒤 : 별명을 붙인 것
mv.price(3)
mv.price_morning(4)
mv.price_soldier(5)
  • import 모듈 as 모듈 별칭 : 모듈 별칭을 지정해 간편한 코드 작성이 가능해집니다.
from theater_module import *
# from random import *
price(3)
price_morning(4)
price_soldier(5)
  • from 모듈 import * : 모듈 안에 있는 전체 함수를 사용할 수 있습니다.
from theater_module import price, price_morning 
# 명시적으로 어떤 함수만 가져올지 정할 수 있음
price(5)
price_morning(6)
# price_solider(7) 쓸 수 없음
  • from 모듈 import 함수명 : 명시적으로 어떤 함수만 가져올지 정할 수 있습니다.
    • 적히지 않은 함수는 사용할 수 없습니다.
from theater_module import price_soldier as price
price(5) # price_solider의 내용을 price로 쓰는 것임
  • from 모듈 import 함수명 as 함수 별칭 : 함수명을 함수 별칭으로 지정해 사용할 수 있습니다.

패키지Permalink


: 모듈을 디렉토리 형식으로 구조화한 것

  • 항상 __init__.py 파일이 존재해야합니다.

Travel 패키지Permalink

# travel 파일 내 thailand.py
class ThailandPackage:
    def detail(self):
        print("[태국 패키지 3박 5일] 방콕, 파타야 여행 (야시장 투어) 50만원")
# travel 파일 내 vietnam.py
class VietnamPackage:
    def detail(self):
        print("[베트남 패키지 3박 5일] 다낭 효도 여행 60만원")
# travel 파일 내 __init__.py
__all__ = ["vietnam", "thailand"]
  • __all__ : import * 를 했을 시에 어떤 모듈을 import 할 지 정의합니다.

외부에서 패키지 사용Permalink

# 패키지.py
import travel.thailand # 모듈이나 패키지만 가능함
# import travel.thailand.ThailandPackage() # 이런 식으로는 사용 불가능함
trip_to = travel.thailand.ThailandPackage()
trip_to.detail()
  • import travel.thailand : 모듈이나 패키지만 가능하고 클래스는 쓸 수 없습니다.
# 패키지.py
from travel.thailand import ThailandPackage # 모듈, 패키지, 클래스 모두 쓸 수 있음
trip_to = ThailandPackage()
trip_to.detail()
  • from 모듈/패키지 import 클래스 : 모듈, 패키지, 클래스를 모두 쓸 수 있습니다.
from travel import vietnam
trip_to = vietnam.VietnamPackage()
trip_to.detail()
  • from 파일 import 패키지명 : 파일과 패키지명을 따로 분리해 쓸 수 있습니다.

__all__Permalink

# __all__ #
from travel import * # 공개 범위를 설정해야함
trip_to = vietnam.VietnamPackage()
trip_to = thailand.ThailandPackage()
trip_to.detail()
  • __all__을 이용해 from travel import * 에서 공개 범위를 설정합니다.

inspectPermalink

import inspect
import random
print(inspect.getfile(random))
print(inspect.getfile(thailand))
  • inspect 모듈 : 모듈, 클래스, 메서드, 함수, 트레이스백, 프레임 객체 및 코드 객체와 같은 라이브 객체에 대한 정보를 얻는 데 도움이 되는 몇 ㅏ지 유용한 함수 제공

  • inspect.getfile(object) : 객체가 정의된 (텍스트나 바이너리)파일의 이름을 반환합니다.

Pip InstallPermalink


# BeautifulSoup4
from bs4 import BeautifulSoup
soup = BeautifulSoup("<p>Some<b>bad<i>HTML")
print(soup.prettify())
  • pip install BeautifulSoup4 : BeautifulSoup4를 다운로드합니다.
    • 코드 내에서 사용 가능해집니다.
  • pip list : Package의 목록을 보여줍니다.
  • pip show beautifulsoup4 : beautifulsoup4 패키지의 정보를 보여줍니다.

  • pip install –upgrade beautifulsoup4 : beautifulsoup4의 업그레이드를 진행합니다.
  • pip uninstall beautifulsoup4 : beautifulsoup4 패키지를 삭제합니다.
    • 코드 내에서 사용 불가능해집니다.

Leave a comment