global dictionary within a class python

試著忘記壹切 提交于 2021-02-08 02:42:48

问题


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

回答1:


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.




回答2:


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 ()
    ....


来源:https://stackoverflow.com/questions/13411668/global-dictionary-within-a-class-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!