写一个水果购物车代码
时间: 2024-11-19 12:14:57 浏览: 10
好的,这里是一个简单的 Python 购物车代码示例,使用了字典来存储商品和它们的数量:
```python
class FruitBasket:
def __init__(self):
self.items = {} # 使用字典存储水果及其数量
def add_fruit(self, fruit, quantity):
if fruit in self.items:
self.items[fruit] += quantity
else:
self.items[fruit] = quantity
def remove_fruit(self, fruit, quantity=1):
if fruit in self.items and self.items[fruit] >= quantity:
self.items[fruit] -= quantity
if self.items[fruit] == 0:
del self.items[fruit]
def total_cost(self, price_dict): # 假设价格信息存储在一个字典中
return sum(price_dict.get(fruit, 0) * self.items.get(fruit, 0) for fruit in self.items)
# 示例用法
price_dict = {
"苹果": 5,
"香蕉": 3,
"橙子": 4,
}
basket = FruitBasket()
basket.add_fruit("苹果", 2)
basket.add_fruit("香蕉", 4)
print(basket.total_cost(price_dict)) # 输出:23 (假设苹果5元一个,香蕉3元一个)
# 如果想删除部分商品
basket.remove_fruit("香蕉", 2)
print(basket.total_cost(price_dict)) # 输出:17 (苹果5*2 + 橙子4*1)
```
阅读全文