写一个简单的商品信息和购物车系统
时间: 2024-11-24 20:40:34 浏览: 5
创建一个简单的商品信息和购物车系统通常涉及定义商品类(Product)和购物车类(ShoppingCart)。这里我会给你一个基本的概念和代码框架。
首先,我们来定义一个商品类(Product),它包含基本信息如名称、价格和库存:
```python
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def description(self):
return f"Name: {self.name}, Price: {self.price}, Stock: {self.stock}"
```
然后,我们可以为购物车添加功能,比如添加商品(add_item)、移除商品(remove_item)以及查看购物车内容:
```python
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, product, quantity=1):
if product.stock >= quantity:
product.stock -= quantity
self.items.append((product, quantity))
else:
print(f"Not enough stock for {product.name}")
def remove_item(self, product_name, quantity=1):
for item in self.items:
if item[0].name == product_name and item[1] >= quantity:
item[0].stock += quantity
item[1] -= quantity
if item[1] == 0:
self.items.remove(item)
break
else:
print(f"{product_name} not found in the cart.")
def show_cart(self):
total_price = 0
for product, q in self.items:
total_price += product.price * q
print(f"Cart contents: {', '.join([p.description() for p, _ in self.items])}")
print(f"Total price: {total_price}")
```
现在你可以使用这两个类来创建商品和购物车实例,进行操作了:
```python
# 创建商品
apple = Product("Apple", 1.5, 10)
banana = Product("Banana", 0.5, 20)
# 创建购物车
cart = ShoppingCart()
# 添加商品到购物车
cart.add_item(apple, 3)
cart.add_item(banana, 5)
# 查看购物车
cart.show_cart()
# 移除商品
cart.remove_item("Apple", 2)
# 再次查看购物车
cart.show_cart()
```
阅读全文