python实现简单的超市商品销售管理代码
时间: 2023-08-26 21:03:52 浏览: 41
以下是一个简单的超市商品销售管理代码示例,使用 Python3 实现:
```python
# 商品类
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __str__(self):
return "商品名:{},价格:{},库存:{}".format(self.name, self.price, self.stock)
# 减少库存
def decrease_stock(self, amount):
if self.stock >= amount:
self.stock -= amount
return True
else:
return False
# 超市类
class Supermarket:
def __init__(self):
self.products = [] # 商品列表
# 添加商品
def add_product(self, product):
self.products.append(product)
# 展示所有商品
def show_all_products(self):
for product in self.products:
print(product)
# 根据商品名查找商品
def find_product_by_name(self, name):
for product in self.products:
if product.name == name:
return product
return None
# 购买商品
def buy_product(self, name, amount):
product = self.find_product_by_name(name)
if product is None:
print("商品不存在")
return False
elif product.decrease_stock(amount):
print("购买成功,总价为:{}".format(product.price * amount))
return True
else:
print("库存不足")
return False
# 主程序
if __name__ == '__main__':
# 创建超市对象
supermarket = Supermarket()
# 添加商品
p1 = Product("可乐", 3.5, 100)
p2 = Product("薯片", 6.0, 50)
p3 = Product("巧克力", 10.0, 30)
supermarket.add_product(p1)
supermarket.add_product(p2)
supermarket.add_product(p3)
# 展示所有商品
print("所有商品:")
supermarket.show_all_products()
# 购买商品
print("购买商品:")
supermarket.buy_product("可乐", 3)
supermarket.buy_product("薯片", 2)
supermarket.buy_product("巧克力", 5)
# 再次展示所有商品
print("所有商品:")
supermarket.show_all_products()
```
该代码中定义了两个类,分别代表商品和超市。商品类包含商品的名称、价格和库存信息,超市类包含商品列表以及一系列操作,如添加商品、展示所有商品、根据商品名查找商品和购买商品等。在主程序中,我们创建了超市对象并添加了三种商品,然后展示了所有商品并购买了一些商品,最后再次展示了所有商品。