카테고리 없음

파이썬 모듈화에 대하여..

초롱씨 2023. 11. 8. 16:48
728x90
반응형

파이썬 메소드 모듈화: 코드를 구성하고 유지보수하기 쉽게 만들기 위해 함수와 클래스를 모듈로 나누는 프로그래밍 기법.

이를 통해 코드의 재사용성을 높일 수 있고, 복잡한 프로그램을 더 쉽게 관리할 수 있다!

모듈(Module): 파이썬에서 모듈은 변수, 함수, 클래스 등을 담고 있는 파일. 모듈은 .py 확장자를 가지고 있어야 하며, 다른 파이썬 파일에서 불러와(import) 사용할 수 있다.

함수 (Functions)와 클래스 (Classes): 모듈화를 통해 함수와 클래스를 별도의 모듈로 분리할 수 있다. 이렇게 분리한 함수와 클래스는 다른 파이썬 파일에서 임포트하여 사용할 수 있다.

네임스페이스 (Namespace): 모듈을 사용하면 각 모듈은 자체의 네임스페이스를 가진다. 따라서 서로 다른 모듈에서 동일한 이름의 함수나 변수를 사용해도 각 모듈의 네임스페이스에 따라 구분된다.

요약하자면 메소드 모듈화를 통해 프로젝트의 코드를 더 관리하기 쉽게 만들 수 있으며, 코드의 가독성을 높이고 재사용성을 높일 수 있다. 이렇게 모듈화된 코드는 프로젝트 규모가 큰 경우에 특히 유용하며, 코드의 유지보수성을 높여준다!!

 

from cust.insert.do_insert import do_I
from cust.delete import do_delete as do_d
from cust.read import do_c as do_c
from cust.read import do_n as do_n
from cust.read import do_p as do_p
from cust.update import do_update as do_u
from cust.common.common import print_menu


customers = list()
index = -1


while True:
    menu = print_menu()
    if menu == 'I':
        index = do_I(customers)
    elif menu == 'P':
        index = do_p.do_P(customers, index)
    elif menu == 'C':
        do_c.do_C(customers, index)
    elif menu == 'N':
        index = do_n.do_N(customers, index)
    elif menu == 'U':
        do_u.do_U(customers, index)
    elif menu == 'D':
        index = do_d.do_D(customers, index)
    elif menu == 'Q':
        print('안녕히 가세요~')
        break
    else:
        print('잘못 입력했 습니다. 다시 입력해 주세요. ')

 

 

메소드를 직접 지정하여 메소드 단위로 import 할 수도 있다.

 

 

def print_menu():
    return input('''다음 중에서 하실 작업의 메뉴를 입력하세요.
        I - 고객 정보 입력 P - 이전 고객 정보 조회 C - 현재 고객 정보 조회 N - 다음 고객 정보 조회
        U - 현재 고객 정보 수정 D - 현재 고객 정보 삭제 Q - 프로그램 종료 ''').upper()

def chk_input_data(msg,func, upper = True):
    while True:
        x = input(msg)
        if upper:
            x = x.upper()
        if func(x):
            break
        else:
            print("잘못 입력하였습니다. 다시 입력해주세요.")

    return x

 

from cust.common.common import chk_input_data


def do_I(customers):
    print('고객정보 입력')
    customer = { 'name': '', 'gender': '', 'email' : '', 'year': 0 }
    customer['name'] = chk_input_data('이름을 입력하세요 : ', lambda x: True if len(x) > 2 else False)
    customer['gender'] = chk_input_data("성별 (M/F)를 입력하세요: ", lambda x: True if x in ('M', 'F') else False)
    customer['email'] = chk_input_data('이메일 주소를 입력하세요 : ', lambda x: True if '@' in x else False, False)
    customer['year'] = chk_input_data('출생년도 4자리 입력하세요 : ', lambda x: True if len(x) == 4 and x.isdigit() else False)
    customers.append(customer)
    index = len(customers) - 1
    return index

 

 

모듈화를 경험해 봤다면 다른 사람이 만든 것도 사용해볼 차례!

라이브러리에 대해 알아보자.

 

# 라이브러리
- 다른 사람들이 만들어 둔 함수들의 모음.
- 자주 사용하는 기능을 쉽게 재사용할 수 있고 다른 사람과도 공유..
- 표준 라이브러리 : 파이썬이 설치될 때 자동으로 설치되는 라이브러리
- 외부 라이브러리: 기본 외에 별도로 설치해서 사용하는 라이브러리
- 외부 라이브러리 설치 법 : pip install 라이브러리 명, conda install 라이브러리명
- 사용법 : import 라이브러리 명
- 설치된 라이브러리 목록 pip list
from datetime import datetime
from pytz   import timezone
from datetime import timedelta

 

print(datetime.now())

2023-11-08 15:26:40.454476

 

print(datetime.now(timezone('UTC')))
print(datetime.now(timezone('Asia/Seoul')))

2023-11-08 06:28:44.590370+00:00

 

x = (datetime.now(timezone('Asia/Seoul')))
print(type(x))
print(x.year)

<class 'datetime.datetime'>
2023

 

print(x.date(), x.time())
print(x.weekday())  # 0이 월요일

2023-11-08 15:30:35.086193
2

 

print(x.strftime('%Y년 %m월 %d일'))
help('datetime.datetime.strftime')

2023년 11월 08일
Help on method_descriptor in datetime.datetime:

datetime.datetime.strftime = strftime(...)
    format -> strftime() style string.

 

x= datetime.strptime('2023-11-02', '%Y-%m-%d')
x.day
print(x - timedelta(days=8))

2023-10-25 00:00:00

 

from dateutil.relativedelta import relativedelta
print(x - relativedelta(months=2))
print(x + relativedelta(years=2))

2023-09-02 00:00:00
2025-11-02 00:00:00

 

import math
math.pi

3.141592653589793

 

 

라이브러리를 활용하여 고객 정보 저장기능을 만들어 보자.

 

 

from cust.insert.do_insert import do_I
from cust.delete import do_delete as do_d
from cust.read import do_c as do_c
from cust.read import do_n as do_n
from cust.read import do_p as do_p
from cust.update import do_update as do_u
from cust.common.common import print_menu
from cust.save.do_save import do_save
from cust.load.do_load import do_load

customers, index = do_load()

while True:
    menu = print_menu()
    if menu == 'I':
        index = do_I(customers)
    elif menu == 'P':
        index = do_p.do_P(customers, index)
    elif menu == 'C':
        do_c.do_C(customers, index)
    elif menu == 'N':
        index = do_n.do_N(customers, index)
    elif menu == 'U':
        do_u.do_U(customers, index)
    elif menu == 'D':
        index = do_d.do_D(customers, index)
    elif menu == 'S':
        do_save(customers)
    elif menu == 'Q':
        do_save(customers)
        print('안녕히 가세요~')
        break
    else:
        print('잘못 입력했습니다. 다시 입력해 주세요. ')

 

import pickle


def do_save(customers):
    with open('./cust/customer_list.pickle', 'wb') as file:
        pickle.dump(customers, file)
        print("고객정보를 저장했습니다.")
import pickle


def do_load():
    customers = list()
    index = -1
    try:
        with open('./cust/customer_list.pickle', 'rb') as file:
            data = pickle.load(file)
            if data:
                print("저장된 고객 데이터를 불러왔습니다.")
                print(data)
                customers = data
                index = len(data)-1

    except FileNotFoundError:
        print("파일이 존재하지 않습니다.")

    return customers, index

 

728x90
반응형