如果要遍历 该类 ,则必须定义一个支持迭代的元类。
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)[...]@classmethoddef 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对象。



