본문 바로가기
파이썬 이야기

Part 33. 파이썬의 모듈과 패키지

by 핸들이없는8톤트럭 2022. 8. 7.
반응형

파이썬 모듈과 패키지

하나의 소스 코드 파일에 모든 프로그램을 구현하면, 라인 수가 많아지고 코드의 구조를 파악하기 어려워집니다. 모듈과 패키지를 이용하면 구조적으로 파이썬 소스 코드를 나누어 구현할 수 있습니다.

- 모듈(module) : 전역변수, 함수, 클래스 등을 모아둔 .py 파일

- 패키지(Package) : 모듈을 디렉토리 폴더로 구조화한 것

# 모듈
# mypkg/module.py
def myfunc():
    print('my_function')


# main.py --> 프로그램

import mypkg.module
import mypkg.module as m
from mypkg import module
from mypkg.module import myfunc

mypkg.module.myfunc()
m.myfunc()
module.myfunc()
myfunc()

 

 

모듈과 패키지로 구현하기

모듈과 패키지로 구현할 때 준수할 사항이 있는데요. 다음과 같습니다.

- 모든 패키지에는 __init__.py 파일이 필요합니다. --> 필수 사항은 아니나, 만드는 것을 권장드립니다.

- 모듈과 패키지 구조는 직관적으로 이해할 수 있게 설계합니다.

 

간단간 계산기를 모듈과 패키지로 구현하기

- 사칙 연산 모듈 구현(add,sub,multi,div)

- 선형 대수 모듈(inner,matmul)

- 통계 모듈(mean, sum)

 

위의 예시를 구현하기 위해서는 calculator라는 패키지가 필요하겠네요. 그리고, 그 안에 모듈이 필요합니다.

1. 사칙연산 모듈

2. 선형 대수 모듈

3. 통계 모듈

3가지의 모듈을 구현합시다.

 

# arithmatic.py
def add(x,y):
    return x+y

def sub(x,y):
    return x-y

def mult(x,y):
    return x*y

def div(x,y):
    return x/y

 

# linear.py
def inner(x,y) :
    ret = 0
    for x_,y_ in zip(x,y):
        ret += x_*y_
    return ret

def matmvl(x,y):
    print('Not supported')

 

# stats.py
def mean(*args):
    return sum(args)/ len(args)

def median(*args):
    x=sorted(args)
    return x[len(x)//2]
import calculator.arithmatic
import calculator.linear as l
from calculator.stats import mean, median

print(calculator.arithmatic.add(4,6))
print(calculator.arithmatic.sub(4,6))
print(calculator.arithmatic.mult(4,6))
print(calculator.arithmatic.div(4,6))

print(l.inner([1,2,3,4],[5,6,7,8]))
l.matmvl([],[])

print(mean(5,3,4,5,123,123))
print(median(1,23,125,12,4,235,34,645,7,67))

 

반응형

댓글