简体   繁体   中英

How to get class instance using assigned “id” variable?

Is it possible to get the wooden_sword object using the id variable in the Item class?

class Item:
    __ids = count(0)

    def __init__(self):
        self.id = next(self.__ids)


class Weapon(Item):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)


wooden_sword = Weapon()

Have the __init__ of Item store to a shared (class attribute) WeakValueDictionary and you can do lookup that way from an alternate constructor ( classmethod ):

import weakref

class Item:
    id_to_item = weakref.WeakValueDictionary()
    __ids = count(0)

    def __init__(self):
        self.id = next(self.__ids)
        self.id_to_item[self.id] = self

    @classmethod
    def from_id(cls, id):
        return cls.id_to_item[id]

Item.from_id can raise an exception (probably KeyError like a normal dict ; test it) if the object corresponding to that id has been garbage collected; using a plain dict would avoid that issue, though it risks memory "leaks" (not a real leak; the object is available, but might never be used again).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM