如何使此方法更新每次调用的数量

时间:2017-02-23 13:27:32

标签: python

class Store(object):
     def __init__(self) :
         self.total_cost=0
         self.goods={} 
     def add_goods(self,goods_name,quantity,cost) :
         cost=cost*quantity
         self.total_cost=self.total_cost+cost
         self.goods[goods_name]=quantity
Q_store=Store()
Q_store.add_goods('shirt',5,10) 
print (Q_store.goods)
print (Q_store.total_goods) 
# it resulted to {'shirt':5} 
# total_goods= 50
Q_store.add_goods('shirt', 5,10)
print (Q_store.goods) 
# it's quantity  remains 5
# the answer remains 5

在重新调用方法和打印时,其数量仍为5而不是10。 如何启用该方法以在每次调用时保持调整数量?因为似乎数量保持不变。提前谢谢。

1 个答案:

答案 0 :(得分:0)

你在这里:

class Store(object):
     def __init__(self) :
         self.total_cost=0
         self.goods={}
         self.total_goods = ()
     def add_goods(self,goods_name,quantity,cost) :
         cost*=quantity 
         self.total_cost+=cost
         if goods_name in self.goods:
            self.goods[goods_name]+=quantity
         else:
            self.goods[goods_name]=quantity

Q_store=Store()
Q_store.add_goods('shirt',5,10) 
print (Q_store.goods)
print (Q_store.total_cost)  
Q_store.add_goods('shirt', 5,10)
print (Q_store.goods) 
print (Q_store.total_cost)  

我将您的代码更改为工作代码。你缺少的是+ =货物词典。