Python 모듈과 패키지 기본개념

2022-03-14

.

Python_studynote(20220314)

[학습자료]

패스트 캠퍼스 “초격차 패키지 : 한 번에 끝내는 파이썬 웹 개발” 강의를 공부하고 정리한 내용입니다.

** URL : https://fastcampus.co.kr/dev_online_pyweb

[학습내용]

  • 모듈을 사용하는 이유

프로그램을 구현할때 기능별로 파일을 나누어서 유지보수 등 관리를 편하게 하기 위함이다.

  • 모듈의 개념

한개의 완성된 프로그램 파일

  • 파이썬 기본 모듈 사용방법
import 모듈이름           import math

모듈이름.변수              print(math.pi)       

모듈이름.함수()            print(math.ceil(5.7))

예를들어서 위에처럼 가져온 모듈에서 math 도 붙이기 싫으면 아래처럼 가져와서 사용해도 된다.

from math import pi, ceil

print(pi)

print(ceil(5.7))

pay_module.py 라는 모듈을 만들고 이를 외부에서 사용하는 실습을 해보자.

먼저 pay_module.py 는 아래와 같다.

# 결제 정보, 관리 모듈
# 변수
version = 2.0

# 함수
def printAuthor():
    print("스타트코딩")

# 클래스
class Pay:
    def __init__(self, id, price, time):
        self.id = id
        self.price = price
        self.time = time
    def get_pay_info(self):
        return f"{self.time} {self.id} {self.price}"

# 해당 파일을 직접 실행했을 때만 실행된다.
if __name__ == "__main__":
    print("pay module 실행")

print(__name__)

pay_module.py 을 실행하면 결과는 아래와 같다.

pay module 실행
__name__

동일한 디렉토리 안에서 이번에는 main.py를 생성한다.

main.py의 내용은 아래와 같다.

import pay_module

# 변수 사용
print(pay_module.version)

# 함수 사용
pay_module.printAuthor()

# 클래스 사용
# 카드식별 아이디, 금액, 결제일자
pay_info = pay_module.Pay("A1021230", 23000, "2022-03-13")
print(pay_info.get_pay_info())

print(pay_module.__name__)

main.py를 실행하면 아래와 같은 결과가 전시된다.

2.0
스타트코딩
2022-03-13 A1021230 23000
pay_module
  • 패키지란

관련 있는 모듈을 하나의 폴더로 구성해 놓은것

  • 초간단 패키지 구현실습

아래와 같은 폴더구조에 유닛과 관련된 모듈들을 생성하고 unit이라는 패키지를 하나 만들어보자.

startcoding/
    unit/
        __init__.py
        character.py
        item.py
        monster.py
    main.py

startcoding/unit/character.py

def test():
    print("this is a character module")

startcoding/unit/item.py

def test():
    print("this is a item module")

startcoding/unit/monster.py


def test():
    print("this is a monster module")

startcoding/unit/init.py

from . import character, item, monster

startcoding/main.py

# 1. import 패키지.모듈
import unit.character
unit.character.test()

# 2. from 패키지 import 모듈
from unit import item
item.test()
this is a character module
this is a item module

패키지 안에 있는 모든 모듈을 가지고 오고 싶을때가 있을것이다.

예를 들어서 unit 패키지의 모든 모듈을 가져와서 쓰고 싶을때가 분명히 있을것이다.

이럴때는 아래와 같이 구현하면 된다.

먼저 import * 을 사용하기 위해서는 사전에 위에 __init__.py와 같이

from 현재위치(.) import 모듈목록들 을 작성해서 생성을 해두어야 한다.

그런 다음에 아래와 같이 from unit import * 을 이용해서 패키지의 모든 모듈을 가져와서 쓰면된다.

위와 같이 __init__.py를 생성 안하고 import * 을 하게 되면 에러가 발생하니 유의해야 한다.

import unit 형태로 사용하는 것도 마찬가지로 사전에 __init__.py를 먼저 생성해줘야 한다.

startcoding/main.py 를 아래와 같이 수정해서 실행해보자.

# 3. from 패키지 import *
from unit import *
character.test()
item.test()
monster.test()

# 4. import 패키지
import unit
unit.character.test()
unit.item.test()
unit.monster.test()
this is a character module
this is a item module
this is a monster module
this is a character module
this is a item module
this is a monster module