1import weakref
2
3class MyClass:
4
5 _instances = set()
6
7 def __init__(self, name):
8 self.name = name
9 self._instances.add(weakref.ref(self))
10
11 @classmethod
12 def getinstances(cls):
13 dead = set()
14 for ref in cls._instances:
15 obj = ref()
16 if obj is not None:
17 yield obj
18 else:
19 dead.add(ref)
20 cls._instances -= dead
21
22a = MyClass("a")
23b = MyClass("b")
24c = MyClass("c")
25
26del b
27
28for obj in MyClass.getinstances():
29 print obj.name # prints 'a' and 'c'