:定义一个购物车类 ShopCart,有一个属性: 商品列表 itemList,有获取所有商品总价的方法,有获取商品总数量的方法,有添加商品的方法,有根据商品ID 从购物车中删除商品的方法·并创建 3 种以上的商品,放在购物车中并进行测试。
时间: 2023-04-08 20:05:11 浏览: 127
好的,这是一个关于编程的问题,我可以回答。以下是 ShopCart 类的定义:
```python
class ShopCart:
def __init__(self):
self.itemList = []
def getTotalPrice(self):
totalPrice = 0
for item in self.itemList:
totalPrice += item.price * item.quantity
return totalPrice
def getTotalQuantity(self):
totalQuantity = 0
for item in self.itemList:
totalQuantity += item.quantity
return totalQuantity
def addItem(self, item):
self.itemList.append(item)
def removeItemById(self, itemId):
for item in self.itemList:
if item.id == itemId:
self.itemList.remove(item)
break
```
现在我们来创建一些商品并测试购物车类:
```python
class Item:
def __init__(self, id, name, price, quantity):
self.id = id
self.name = name
self.price = price
self.quantity = quantity
item1 = Item(1, "iPhone", 6999, 1)
item2 = Item(2, "MacBook", 9999, 1)
item3 = Item(3, "AirPods", 1299, 2)
cart = ShopCart()
cart.addItem(item1)
cart.addItem(item2)
cart.addItem(item3)
print("Total price:", cart.getTotalPrice())
print("Total quantity:", cart.getTotalQuantity())
cart.removeItemById(2)
print("Total price after removing item 2:", cart.getTotalPrice())
print("Total quantity after removing item 2:", cart.getTotalQuantity())
```
输出结果应该是:
```
Total price: 10596
Total quantity: 4
Total price after removing item 2: 8298
Total quantity after removing item 2: 3
```
阅读全文