编写函数并调用class ShoppingCart: def __init__(self): self.items = {} def add_item(self, item, quantity): if item in self.items: self.items[item] += quantity else: self.items[item] = quantity def remove_item(self, item, quantity): if item in self.items: if self.items[item] <= quantity: del self.items[item] else: self.items[item] -= quantity def get_total(self): total = 0 for item, quantity in self.items.items(): total += item.get_price() * quantity return total def get_item_count(self): count = 0 for quantity in self.items.values(): count += quantity return count def get_items(self): return self.items
时间: 2023-05-17 10:07:43 浏览: 104
好的,以下是你需要的代码:
class ShoppingCart:
def __init__(self):
self.items = {}
def add_item(self, item, quantity):
if item in self.items:
self.items[item] += quantity
else:
self.items[item] = quantity
def remove_item(self, item, quantity):
if item in self.items:
if self.items[item] <= quantity:
del self.items[item]
else:
self.items[item] -= quantity
def get_total(self):
total = 0
for item, quantity in self.items.items():
total += item.get_price() * quantity
return total
def get_item_count(self):
count = 0
for quantity in self.items.values():
count += quantity
return count
def get_items(self):
return self.items
你可以通过以下方式调用它:
cart = ShoppingCart()
cart.add_item(item1, 2)
cart.add_item(item2, 1)
cart.remove_item(item1, 1)
total = cart.get_total()
count = cart.get_item_count()
items = cart.get_items()
请注意,item1和item2是你自己定义的商品对象,get_price()是商品对象的一个方法,用于获取商品价格。
阅读全文