본문 바로가기

Back-End/Python

[Python][파이썬] 고객 정보 관리 시스템 만들기 실습 5 - class, structure, os라이브러리

~ 목차 ~

파이썬에도 class가 있다는 것을 알게 되었고 class를 사용하면 어떤 점들이 좋은지 알아보고

실습 예제를 class를 사용하여 바꾸어 보자.

 

 

클래스를 사용하는 이유

  1. 코드의 구조화 및 조직화: 클래스를 사용하면 코드를 더 모듈화하고 구조화할 수 있다.
  2. 재사용성: 클래스를 사용하면 비슷한 기능을 하는 코드를 여러 곳에서 재사용할 수 있다.
    클래스의 인스턴스를 생성하여 다양한 상황에서 동일한 코드를 사용할 수 있다.
  3. 상태(데이터)와 행동(메서드)의 결합: 클래스는 상태(멤버 변수)와 행동(메서드)을 함께 묶어놓는다.
  4. 추상화 및 캡슐화: 클래스는 객체 지향 프로그래밍의 핵심 개념 중 하나인 추상화와 캡슐화를 제공한다.
    추상화는 복잡한 시스템을 단순화하고 필요한 부분에 중점을 두어 핵심 개념을 강조하는 것을 의미하며,
    캡슐화는 객체의 내부 구현을 외부에서 감추는 것을 의미한다.
  5. 상속을 통한 확장성: 클래스를 사용하면 상속을 통해 새로운 클래스를 만들어 기존 클래스의 기능을 확장할 수 있다. 이는 코드 재사용성과 유연성을 증가시킨다.
  6. 코드의 가독성과 유지보수성 향상: 클래스를 사용하면 코드의 가독성이 향상되며 유지보수가 용이해진다.

 

 

고객 정보 관리 시스템 Class화 하기

0. class 선언 :
    class Customer:

 

1. 모듈에 있는 함수들 class안에 가져오기
    def print_menu(self):
    def chk_input_data(self, msg, func, upper=True):

    def do_S(self, customers):

    def do_L(self):

 

2. 필요없는 import 닫아주기

 

3. self 변수 넣기

  • self는 파이썬에서 클래스의 메서드에서 사용되는 첫 번째 매개변수로, 현재 인스턴스를 나타낸다.
  • self를 통해 메서드는 자기 자신의 인스턴스 변수에 접근하고 수정할 수 있다.

 

4. 실행 코드 수정해주기 :
     if __name__ == '__main__':

# from cust.ver1.common import print_menu
from cust.insert.do_I import do_I as I
from cust.read.do_C import do_C as C
from cust.read.do_P import do_P as P
from cust.read.do_N import do_N as N
from cust.update.do_U import do_U as U
from cust.delete.do_D import do_D as D
# from cust.save.do_Save import do_S as S
# from cust.save.do_Save import do_L as L

import pickle
import sys
import os

class Customer:

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

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

    def do_S(self, customers):
        try:
            with open('cust/customers.pickle', 'wb') as fp:
                pickle.dump(customers, fp)
        except Exception as e:
            print('저장하는데에 실패하였습니다.', e)

    def do_L(self):
        file_path = 'cust/customers.pickle'
        if os.path.exists(file_path):
            with open(file_path, 'rb') as fp:
                return pickle.load(fp)
        else:
            return list()

    #main
    def main(self):

        customers = self.do_L()
        index = -1

        while True:
            menu = self.print_menu()
            if menu == 'I':
                print('index before :', index)
                index = I(customers, index)
                print('index :', index)
                print('customers : ', customers)

            elif menu == 'P':
                index = P(customers, index)

            elif menu == 'C':
                C(customers, index)

            elif menu == 'N':
                index = N(customers, index)

            elif menu == 'U':
                U(customers, index)

            elif menu == 'D':
                index = D(customers, index)

            elif menu == 'S':
                self.do_S(customers)

            elif menu == 'Q':
                self.do_S(customers)
                print('저장이 완료되었습니다.')
                print('안녕히가세요~')
                sys.exit()

            else:
                print('잘못 입력하셨습니다. 다시 입력 해주세요')


if __name__ == '__main__':
    a = Customer()
    a.main()

 

 


 

 

알아두면 좋은 기능!!

우리가 쓰는 dataspell에 왼쪽 메뉴에 workspace랑 Structure가 있다.

workspace는 우리가 코드쓰는 작업 공간을 보여 주고

Structure는 우리가 만든 코드들의 구조를 보여 준다.

 

1. Structure

  • 데이터나 코드의 구조
  • c = class, m = method, f = function
  • 클래스 안에 메소드가 활성화 되어있다면 들여쓰기가 잘 된 것

structure

 

2. os 라이브러리

  • 경로 : 워킹디렉토리(워킹 폴더)
  • 현재 내가 쓰고있는 로직의 워킹디렉토리 알려주는 라이브러리 : os
  • os : 파일 경로 확인
    => os.getcwd
  • 경로에 있는 파일 존재 확인
    => os.path.exists(file_path)
import os
os.getcwd()

결과

'C:\\Users\\user\\python_basic'

 

  • 사용 예 : pickle파일 없을 때 반환값 설정
#pickle파일 없을 때 반환값 설정
file_path = 'cust/customerinfo.pickle'
if os.path.exists(file_path):
    with open(file_path, 'rb') as f:
        customerstext = pickle.load(f)
        print('고객정보를 불러옵니다.')
else:
    return list()

 

728x90