Python のクラスを使用してオンラインショッピングカートをシミュレートし、商品の追加・削除などの操作をサポート
Python のクラスを使用してオンラインショッピングカートをシミュレートします。ショッピングカートは、商品の追加、商品の削除、カートの内容の表示、合計金額の計算などの機能をサポートします。
実例
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, name, price, quantity=1):
self.items.append({'name': name, 'price': price, 'quantity': quantity})
def remove_item(self, name):
self.items = [item for item in self.items if item['name'] != name]
def view_cart(self):
if not self.items:
print("Your shopping cart is empty.")
else:
for item in self.items:
print(f"{item['name']} - ${item['price']} x {item['quantity']}")
def calculate_total(self):
return sum(item['price'] * item['quantity'] for item in self.items)
# 使用例
cart = ShoppingCart()
cart.add_item("Apple", 0.5, 3)
cart.add_item("Banana", 0.3, 5)
cart.view_cart()
print(f"Total: ${cart.calculate_total()}")
cart.remove_item("Banana")
cart.view_cart()
print(f"Total: ${cart.calculate_total()}")
def __init__(self):
self.items = []
def add_item(self, name, price, quantity=1):
self.items.append({'name': name, 'price': price, 'quantity': quantity})
def remove_item(self, name):
self.items = [item for item in self.items if item['name'] != name]
def view_cart(self):
if not self.items:
print("Your shopping cart is empty.")
else:
for item in self.items:
print(f"{item['name']} - ${item['price']} x {item['quantity']}")
def calculate_total(self):
return sum(item['price'] * item['quantity'] for item in self.items)
# 使用例
cart = ShoppingCart()
cart.add_item("Apple", 0.5, 3)
cart.add_item("Banana", 0.3, 5)
cart.view_cart()
print(f"Total: ${cart.calculate_total()}")
cart.remove_item("Banana")
cart.view_cart()
print(f"Total: ${cart.calculate_total()}")
コード解析:
__init__メソッドはショッピングカートを初期化し、空のリストを作成します。items商品を保存するためのものです。add_itemメソッドはショッピングカートに商品を追加するために使用され、商品名、価格、数量(デフォルトは1)をパラメータとして受け取り、それをitemsリストに追加します。remove_itemメソッドは、指定された名前の商品をショッピングカートから削除するために使用され、リスト内包表記を使用して不要な商品を除外します。view_cartメソッドは、ショッピングカート内の商品を表示するために使用されます。ショッピングカートが空の場合は、カートが空であることを通知します。それ以外の場合は、itemsリストを走査し、各商品の詳細情報を出力します。calculate_totalメソッドは、ショッピングカート内のすべての商品の合計金額を計算するために使用され、リスト内包表記とsum関数を使用して実装します。
出力結果:
Apple - $0.5 x 3 Banana - $0.3 x 5 Total: $2.4 Apple - $0.5 x 3 Total: $1.5その他の拡張
Python3 実例