python购买商品的程序
时间: 2024-09-09 18:08:48 浏览: 32
在Python中编写一个简单的购物车程序,可以模拟用户选择商品、添加到购物车以及查看总价的过程。这里是一个基础示例:
```python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def total_price(self):
return self.price
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, product):
self.items.append(product)
def remove_item(self, item_name):
for i, product in enumerate(self.items):
if product.name == item_name:
del self.items[i]
break
def get_total_price(self):
total = 0
for item in self.items:
total += item.total_price()
return total
# 示例商品
apple = Product('苹果', 5)
banana = Product('香蕉', 3)
# 购物操作
cart = ShoppingCart()
cart.add_item(apple) # 添加商品
cart.add_item(banana)
print(f"购物车中有:{cart.get_total_items()}")
print(f"总价:{cart.get_total_price()}")
cart.remove_item('苹果') # 移除商品
print("移除苹果后,新的总价:", cart.get_total_price())
阅读全文