2017-02-23 101 views
0
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 我怎樣才能使該方法保持在每個呼叫調整量?因爲它似乎數量保持不變。先謝謝你。我怎樣才能讓這個方法更新每次通話

+0

你能告訴我們你究竟是怎麼稱呼這種方法的? – MaLiN2223

+0

我將Q_store作爲類實例 – Udonse

+0

Q_store.add_goods('shirt',5,10) – Udonse

回答

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) 

我改變你的代碼的工作之一。你錯過的是+ =商品詞典。

+0

謝謝了很多..我沒有認識到..真的很感謝 – Udonse

+0

@Udonse沒問題。只要記住[接受我的這個答案](http://stackoverflow.com/help/someone-answers),如果你認爲這是正確的。 – MaLiN2223

+0

謝謝..非常感謝您的協助 – Udonse