如果你想迭代类,你必须定义一个支持迭代的元类。
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
字典中。weakref
当你
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
对象。