写一个购物管理模块其中包括显示所有商品信息,查询商品详细信息,添加购物车,清空购物车,购物车结算
时间: 2023-10-16 22:09:01 浏览: 170
购物车模块
好的,以下是一个简单的购物管理模块:
```python
class Product:
def __init__(self, name, price, description):
self.name = name
self.price = price
self.description = description
def __str__(self):
return f"{self.name} - ${self.price}\n{self.description}"
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
self.items.remove(item)
def clear_cart(self):
self.items = []
def calculate_total(self):
total = 0
for item in self.items:
total += item.price
return total
class ProductCatalog:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def find_product(self, name):
for product in self.products:
if product.name == name:
return product
return None
def display_products(self):
for product in self.products:
print(product)
print()
# 创建商品目录
catalog = ProductCatalog()
# 添加商品
catalog.add_product(Product("iPhone X", 999, "The latest iPhone from Apple."))
catalog.add_product(Product("Samsung Galaxy S9", 899, "The latest Samsung smartphone."))
catalog.add_product(Product("Google Pixel 2", 799, "The latest Google smartphone."))
# 显示所有商品信息
catalog.display_products()
# 查询商品详细信息
product = catalog.find_product("iPhone X")
if product:
print(product)
else:
print("Product not found")
# 创建购物车
cart = ShoppingCart()
# 添加商品到购物车
cart.add_item(catalog.find_product("iPhone X"))
cart.add_item(catalog.find_product("Samsung Galaxy S9"))
# 清空购物车
cart.clear_cart()
# 结算购物车
total = cart.calculate_total()
print(f"Total: ${total}")
```
以上代码只是一个简单的购物管理模块,可以根据具体需求进行修改和扩展。
阅读全文