I’m designing an inventory class in Python, it is supposed to keep track of the items a store has in stock, add new ones, and delete them, as well.
The trouble comes from my “item” definitions within the class. When I add another item to my dictionary, it replaces it, it doesn’t add it. I appreciate your help! Why won’t it add???
class Store:
def __init__(self, name, email):
self.name = name
self.email = email
# two accessor methods
def getName(self):
return self.name
def getEmail(self):
return self.email
# makes print work correctly
def __str__(self):
return str(self.name)
# items
def additem(self, item, price):
global items
items = {}
self.item = str(item)
self.price = float(price)
items[self.item] = price
def delitem(self, item):
items.remove(item)
def displayinventory(self):
return items
You are setting
itemsto a new empty dictionary every time you calladditem. So it always erases whatever’s there before adding a new item. Instead, setitems = {}once outside the function. There is also no point in doingself.item = str(item)(and the same for the price), because this will just overwrite the existingself.item, so you’ll only have access to the most recent one.Actually, what you probably should do is make
itemsan attribute of the object, like this:The way you’re doing it, there’s only one global
itemsdict that will be shared among all Stores. The above way gives each store its own items dict so it can keep its own record of its own items.