您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我可以遍历Python中的类吗?

我可以遍历Python中的类吗?

如果要遍历 该类 ,则必须定义一个支持迭代的元类

x.py:

class it(type):
    def __iter__(self):
        # Wanna iterate over a class? Then ask that class for iterator.
        return self.classiter()

class Foo:
    __Metaclass__ = it # We need that Meta class...
    by_id = {} # Store the stuff here...

    def __init__(self, id): # new isntance of class
        self.id = id # do we need that?
        self.by_id[id] = self # register istance

    @classmethod
    def classiter(cls): # iterate over class by giving all instances which have been instantiated
        return iter(cls.by_id.values())

if __name__ == '__main__':
    a = Foo(123)
    print list(Foo)
    del a
    print list(Foo)

最终您将看到,删除实例不会对对象本身产生任何影响,因为它保留在by_id字典中。您可以使用weakrefs来应对

import weakref

然后做

by_id = weakref.WeakValueDictionary()

。这样,仅在存在“强”引用的a情况下才保留值,例如在这种情况下。在之后del a,只有弱引用指向该对象,因此可以对其进行gc’ed。

由于有关WeakValueDictionary()s的警告,我建议使用以下命令:

[...]
    self.by_id[id] = weakref.ref(self)
[...]
@classmethod
def classiter(cls):
    # return all class instances which are still alive according to their weakref pointing to them
    return (i for i in (i() for i in cls.by_id.values()) if i is not None)

看起来有点复杂,但是要确保您得到的是对象而不是weakref对象。

python 2022/1/1 18:41:29 有288人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶