python简单购物车代码
时间: 2024-05-06 08:12:53 浏览: 76
当然可以!以下是一个简单的Python购物车代码示例:
```python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def remove_product(self, product):
self.products.remove(product)
def calculate_total(self):
total = 0
for product in self.products:
total += product.price
return total
# 创建商品对象
product1 = Product("手机", 2000)
product2 = Product("电视", 5000)
product3 = Product("耳机", 100)
# 创建购物车对象
cart = ShoppingCart()
# 添加商品到购物车
cart.add_product(product1)
cart.add_product(product2)
cart.add_product(product3)
# 计算购物车总价
total_price = cart.calculate_total()
print("购物车总价:", total_price)
```
阅读全文