finding name of instances created

Ryan Paul segphault at sbcglobal.net
Mon Jan 24 08:19:45 EST 2005


On Fri, 21 Jan 2005 16:13:19 -0800, André wrote:

> Short version of what I am looking for:
> 
> Given a class "public_class" which is instantiated a few times e.g.
> 
> a = public_class()
> b = public_class()
> c = public_class()
> 
> I would like to find out the name of the instances so that I could
> create a list of them e.g.
> ['a', 'b', 'c']
> 


A working solution:

class A:
  pass

a = A()
b = A()
c = A()

[x for x,y in locals().items() if
  hasattr(y,"__class__") and y.__class__ == A]

That said, you probably dont want to do it. I doubt that it will work
consistently.

BTW, based on my understanding of the other stuff you said, this is
probably not the best way to do whatever it is you are trying to do.

--SegPhault







More information about the Python-list mailing list