实现一个简单的Python购物车模块,你可以按照以下步骤进行:
1. 定义商品类(`Product`),包含商品名称(`name`)和价格(`price`)。
2. 定义购物车类(`ShoppingCart`),包含添加商品(`add_product`)、删除商品(`remove_product`)和计算总价(`calculate_total`)的方法。
3. 创建商品实例并添加到购物车中。
4. 用户可以输入购买的商品,程序会更新购物车并计算总价。
5. 用户可以输入退出命令,程序将打印出购物车中的商品和剩余金额。
下面是一个简单的示例代码:
```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("苹果", 5)
product2 = Product("香蕉", 3)
product3 = Product("橙子", 2)
创建购物车实例
cart = ShoppingCart()
添加商品到购物车
cart.add_product(product1)
cart.add_product(product2)
cart.add_product(product3)
用户输入购买的商品序号
while True:
print("请输入要购买的商品序号(输入n退出,输入q退出程序):")
choice = input()
if choice.lower() == 'q':
break
if choice.isdigit() and 0 < int(choice) <= len(cart.products):
index = int(choice) - 1
if cart.products[index] in cart.products:
cart.remove_product(cart.products[index])
print(f"商品 {cart.products[index].name} 已从购物车中移除。")
else:
print(f"商品序号 {choice} 无效。")
else:
print("无效的输入,请输入数字序号。")
打印购物车中的商品和总价
print("购物车中的商品:")
for product in cart.products:
print(f"{product.name} - ¥{product.price}")
print(f"购物车总价:¥{cart.calculate_total()}")
这个示例代码展示了如何创建商品和购物车实例,如何添加和删除商品,以及如何在用户输入后更新购物车内容并计算总价。用户可以通过输入特定的命令来退出程序。
如果你需要更复杂的功能,比如用户认证、商品库存管理、多用户支持等,你可以在此基础上进行扩展。