Possible Duplicate:
Printing all instances of a class
Is there a way to return every instance of a special class? I'd like to get some attributes of every object and afterwards delete the object.
Possible Duplicate:
Printing all instances of a class
Is there a way to return every instance of a special class? I'd like to get some attributes of every object and afterwards delete the object.
Is the class one you are writing yourself?
Here is a short example of keeping track of instances:
class Tracker(object):
instances = list()
def __init__(self):
self.__class__.instances.append(self)
@classmethod
def projeny(cls):
print "There are currently %d instances of Tracker" % len(cls.instances)
for instance in cls.instances:
print instance
t1 = Tracker()
t2 = Tracker()
Tracker.projeny()
t3 = Tracker()
Tracker.projeny()
which gives us:
There are currently 2 instances of Tracker
<__main__.Tracker object at 0x02237A30>
<__main__.Tracker object at 0x02237AD0>
There are currently 3 instances of Tracker
<__main__.Tracker object at 0x02237A30>
<__main__.Tracker object at 0x02237AD0>
<__main__.Tracker object at 0x02237AF0>
See this answer for a robust implementation.