0

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.

Community
  • 1
  • 1
wewa
  • 1,628
  • 1
  • 16
  • 35

1 Answers1

2

Is the class one you are writing yourself?

  • Yes: design it to keep track of its instances -- then you can query that cache
  • No: no good way.

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.

Community
  • 1
  • 1
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Yes I write the class myself. Could you explain what you mean by "keep track of instances"? – wewa Sep 26 '12 at 07:48