管理购物车Python
时间: 2024-05-27 18:06:35 浏览: 13
管理购物车Python可以通过创建一个购物车类,实现添加商品、删除商品、修改商品数量、计算总价等功能。以下是一个简单的购物车类的示例代码:
```
class ShoppingCart:
def __init__(self):
self.items = {}
def add_item(self, item_name, quantity, price):
if item_name not in self.items:
self.items[item_name] = {'quantity': quantity, 'price': price}
else:
self.items[item_name]['quantity'] += quantity
def remove_item(self, item_name, quantity):
if item_name in self.items:
if quantity >= self.items[item_name]['quantity']:
del self.items[item_name]
else:
self.items[item_name]['quantity'] -= quantity
def change_item_quantity(self, item_name, quantity):
if item_name in self.items:
self.items[item_name]['quantity'] = quantity
def calculate_total_price(self):
total = 0
for item in self.items.values():
total += item['quantity'] * item['price']
return total
```
使用该类,可以实现以下功能:
1. 添加商品:调用add_item方法,传入商品名称、数量和单价;
2. 删除商品:调用remove_item方法,传入商品名称和要删除的数量;
3. 修改商品数量:调用change_item_quantity方法,传入商品名称和新的数量;
4. 计算总价:调用calculate_total_price方法,返回购物车中所有商品的总价。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)