如何使此方法更新每个

2024-04-25 22:41:52 发布

您现在位置: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

在重新调用该方法并打印时,其数量由10变为5。 如何使方法在每次调用时不断调整数量?因为数量似乎保持不变。先谢谢你


Tags: storenameselfadd数量defitquantity
1条回答
网友
1楼 · 发布于 2024-04-25 22:41:52

给你:

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)  

我把你的密码改成了工作密码。你缺少的是一本商品词典

相关问题 更多 >