我正在运行此代码,当我将物品添加到库存时,该物品出现在所有库存类中,我在哪里出错了?一旦我运行 Browse(),添加新库存,向其中添加项目,当我创建新库存时,第一个库存中的项目默认出现在新库存中。我该如何解决这个问题男孩和女孩?inventories = {}class Inventory: ##Class for new inventory inventory = {} items = {} def __init__(self,name): self.name = name def add_item(self,item,price,amount): if item in self.items: return False else: self.items[item] = int(price) self.inventory[item] = int(amount) return True def add_amount(self,item,amount): self.inventory[item] += amount def update_amount(self,item,amount): self.inventory[item] = amount def remove_amount(self,item,amount): self.inventory[item] -= amount def update_item_price(self,item,price): self.items[item] = price def inv_list(self): ##Print the class print(self.name) print("\nItem: Price: Amount:\n") for item in self.inventory: print(f"{item}\t\t{self.items[item]}\t\t{self.inventory[item]}")def new_inventory(): ##MAkes a new inventory class and stores in inventories{} global inventories while True: answer = input("What would you like to call your new Inventory?") if answer in inventories: print("Name already taken") continue inventories[answer] = Inventory(answer) print("Inventory created") update(answer) break
1 回答
慕哥9229398
TA贡献1877条经验 获得超6个赞
inventory = {}
items = {}
正在为所有类实例创建共享属性。您应该初始化__init__方法中的属性。
class inventory:
def __init__(self, name):
self.name = name
self.inventory = {}
self.items = {}
添加回答
举报
0/150
提交
取消