Tyler Seymour
Tyler Seymour

Reputation: 617

global dictionary within a class python

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

Upvotes: 3

Views: 35254

Answers (2)

Josef Klotzner
Josef Klotzner

Reputation: 313

Even this was asked a view years ago, others might be interested in this answer. If you want to use a dictionary globally within a class, then you need to define it in section where you use your class. if you are using your class in main, then define it there. A dictionary or o list are global by default.

class Store:

    ...

    def additem (self, item, price):
        self.item = str (item)
        self.price = float (price)
        items [self.item] = price

def main ():
    ...
    items = dict ()
    myStore = Store ()
    ....

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251568

You are setting items to a new empty dictionary every time you call additem. So it always erases whatever's there before adding a new item. Instead, set items = {} once outside the function. There is also no point in doing self.item = str(item) (and the same for the price), because this will just overwrite the existing self.item, so you'll only have access to the most recent one.

Actually, what you probably should do is make items an attribute of the object, like this:

class Store:

    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.items = {}

    # rest of your code here. . .

    def additem(self, item, price):
        self.items[str(item)] = float(price)

    def delitem(self, item):
        del self.items[str(item)]

    def displayinventory(self):
        return self.items

The way you're doing it, there's only one global items dict 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.

Upvotes: 8

Related Questions