본문 바로가기
프로그램

[파이썬] 문제 : 쇼핑몰 Product, ShoppingCart 클래스

by 오디세이99 2023. 4. 3.
728x90
반응형

from wcwidth import wcswidth             # 한글의 출력시 자리수를 맞추기 위한 패키지

class Product:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

    def get_price(self):
        return self.price * self.quantity

    def __str__(self):
        info = f'구매 품목이름: {self.name}, 단가: {self.price}, 수량: {self.quantity}'
        return info


class ShoppingCart:
    def __init__(self):
        self.shop_list = []

    def add(self, product):
        self.shop_list.append(product)

    def delete(self, product, qty):
        for p in self.shop_list:
            if p.name == product.name and product.quantity >= qty:    # 삭제 하려는 제품명이 같고, quantity가 삯제하려는 수 qty보다 클때
                p.quantity -= qty

    def total_price(self):
        total = 0                                   # 구매 합계용 변수
        for i in range(len(self.shop_list)):        # 구매 제품 수 만큼 반복
            total += self.shop_list[i].get_price()  # get_price() 함수를 사용해 총 가격 계산
        return total

    def biling(self):
        print("구입 품목:\n")
        for i in range(len(self.shop_list)):       # 구매 제품 수 만큼 반복
            name = self.shop_list[i].name           # 코딩 문장이 길어져 혼동될 수 있기 때문에 다른 이름으로 값 사용
            qty = self.shop_list[i].quantity
            price = self.shop_list[i].price
            if qty > 0:                             # qty 즉 수량이 0 보다 큰 제품만 영수증 출력
                n_fmt = 26                          # 제품명의 칸 수 지정
                n_cnt = n_fmt - (wcswidth(f"{name:<{n_fmt}}") - n_fmt)     # wcswidth를 사용해 한글 제품명의 칸수를 맞춤
                print(f"{name:<{n_cnt}}    {format(qty,',')}개    {format(price,',')}")   # 출력

        print('-'*44)
        print(f"합계 {format(self.total_price(),','):>38}")
        
    def __srt__(self):
        info = f''
        return info



if __name__ == '__main__':
    cart = ShoppingCart()
    cart.add(Product('제주 삼다수 그린 2L', 1200, 5))
    cart.add(Product('신라면(120g*5입)', 4100, 2))
    cart.add(Product('CJ 햇반(210g*12입)', 13980, 1))
    cart.add(Product('몽쉘크림(12입)', 4780, 1))

    # cart.biling()                                      # 상태 확인용 출력. 잘 입력 되었는지 확인
    
    for p in cart.shop_list:
        if p.name == '몽쉘크림(12입)':                   # 몰쉘의 구입 수량을 0으로 함(구매취소와 같음)
            cart.delete(p, p.quantity)                    # 클래스 규격에 delete 함수는 Product 클래스와 qty를 인수로 하도록 되어 있음
            
    cart.add(Product('해태 구운감자(135g*5입)', 3580, 2))
    
    cart.biling()

728x90
반응형

댓글