简体   繁体   English

如何使用分配的“id”变量获取 class 实例?

[英]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?是否可以使用Item class 中的id变量来获得wooden_sword object?

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 ):Item__init__存储到共享(类属性) WeakValueDictionary ,您可以从备用构造函数( 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;如果对应于该id的 object 已被垃圾收集,则Item.from_id可以引发异常(可能像普通KeyError一样的dict ;测试它); 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).使用普通的dict可以避免这个问题,尽管它有 memory “泄漏”的风险(不是真正的泄漏;object 可用,但可能永远不会再次使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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