方法remove_item需要与add_item类似的参数。它应该删除已添加到购物车中但不是必需的项目。此方法应从当前总计中扣除这些项目的成本,并相应地更新项目dict。如果要删除的商品数量超过购物车中的当前数量,则假定要删除该商品的所有商品。
class ShoppingCart(object):
#constructor
def __init__(self):
self.total = 0
self.items = {}
#method to add items in the shoping cart
def add_item(self,item_name, quantity, price):
self.total += (price * quantity )
self.items[item_name] = quantity
#method to remove items
def remove_item(self,item_name, quantity, price):
keys = self.items.keys()
for keys,v in self.items.items():
if keys == item_name and quantity > self.items[keys]: #if item_name equals iterated item
self.total -= (price * quantity )
del( self.items[keys] )
del(self.items[keys])
self.total -= (quantity * price)
还有要检查的测试单元
def test_add_item_hidden(self):
self.cart.add_item('Mango', 3, 10)
self.cart.add_item('Orange', 16, 10)
self.assertEqual(self.cart.total, 190, msg='Cart total not correct after adding items')
self.assertEqual(self.cart.items['Orange'], 16, msg='Quantity of items not correct after adding item')
方法remove_item
即使在尝试通过dictionary changed size during iteration
进行访问后也会出现keys
错误,如上所示
答案 0 :(得分:3)
我认为remove_item功能可能更简单。
#method to remove items
def remove_item(self,item_name, quantity, price):
if item_name in self.item.keys():
self.total -= (price * quantity)
del self.items[item_name]
使用此版本,您正在检查词典中是否有item_name
,如果是,则表示您要将其删除,并从total
尝试从字典中删除,在迭代时删除它们,通常不是一个好主意。
如果item_name是键列表,我必须假设数量和价格也是如此。 所以可能的功能是:
def remove_item(self,item_name, quantity, price):
for index, value in enumerate(item_name):
if value in self.item.keys():
self.total -= (price[index] * quantity[index])
del self.items[value]
我没有测试但应该工作。
如果想要获得物品的清单。功能应该是这样的。
#method to remove items
def remove_item(self,item_name, quantity, price):
if item_name in self.items.keys():
#remove from total the price for the items
if quantity <= self.items[item_name]:
self.total -= (price * quantity)
else:
self.total -= (price * self.items[item_name])
#if quantity is greater or equal of the current value, item is removed.
if quantity >= self.items[item_name]
del self.items[item_name]
else:
self.items[item_name] -= quantity