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
s来应对
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
对象。