用python实现校园自选超市商品管理系统代码
时间: 2024-12-12 10:07:59 浏览: 13
在Python中实现校园自选超市的商品管理系统,我们可以使用类(class)、字典(dictionary)以及一些基本的数据结构来模拟。这里是一个简单的例子,展示了如何创建商品、购物车和结算功能:
```python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.items = {}
def add_item(self, product_name, quantity):
if product_name in self.items:
self.items[product_name] += quantity
else:
self.items[product_name] = quantity
def remove_item(self, product_name, quantity=1):
if product_name in self.items and self.items[product_name] >= quantity:
self.items[product_name] -= quantity
else:
print(f"Product {product_name} not found or insufficient quantity.")
def total_cost(self):
return sum(product * price for product, price in self.items.items())
class SupermarketSystem:
def __init__(self):
self.products = {
'苹果': Product('苹果', 5),
'香蕉': Product('香蕉', 3),
# 添加更多的产品...
}
def display_products(self):
for name, product in self.products.items():
print(f"{name}: 价格{product.price}")
# 使用示例
system = SupermarketSystem()
system.display_products()
cart = ShoppingCart()
cart.add_item('苹果', 2)
cart.add_item('香蕉', 4)
print("购物车总成本:", cart.total_cost())
cart.remove_item('香蕉', 3)
阅读全文