finding name of instances created
Ryan Paul
segphault at sbcglobal.net
Mon Jan 24 08:29:55 EST 2005
On Mon, 24 Jan 2005 13:19:45 +0000, Ryan Paul wrote:
>
> 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]
>
Just wanted to clarify, because I know that the intellectually deficient
amongst you will say that isinstance is better than using __class__...
In this case isinstance isnt desirable because it will catch
instances of any objects that inherit A, not just instances of A. Observe:
class A: pass
class B(A): pass
a = A()
b = A()
c = A()
d = B()
>>> [x for x,y in locals().items() if isinstance(y,A)]
['a', 'c', 'b', 'd']
>>> [x for x,y in locals().items() if
... hasattr(y,"__class__") and y.__class__ == A]
['a', 'c', 'b']
-- SegPhault
More information about the Python-list
mailing list