[Tutor] Accessing the name of an instance variable - from Edward
Comber
Gregor Lingl
glingl at aon.at
Sun Nov 16 14:25:00 EST 2003
<forwarded to tutor at python.org>
Hi Gregor. I'm not sure how I should reply. I would have thought I should
reply to the list but this seems to go to you.
This works fine - notice change to globals()
file get_name.py
class A:
def __init__(self,x,y):
self.one = x
self.two = y
def describe(self):
print 'Describing'
this_instance = id(self)
for name, instance in globals().items(): # vars()
print name
if isinstance(instance,A):
if id(instance) == this_instance:
print 'Description of', name
print self.one, self.two
if __name__ == '__main__' :
a = A(1,2)
b = A(1001,1002)
a.describe()
b.describe()
But this won't, from another file presumably because of namespace problems.
I hoped globals() would pick up everything but it doesn't appear to.
import get_name
a = get_name.A(1,2)
a.describe()
Eddie
-----Original Message-----
From: Gregor Lingl [mailto:glingl at aon.at]
Sent: 16 November 2003 11:33
To: Eddie Comber
Subject: Re: [Tutor] Accessing the name of an instance variable
Eddie Comber schrieb:
>For debugging purposes, I would like to be able to print the name of some
>instances of classes directly from the program, together with the class
>data. The data is of course simple but getting the name is a problem to me.
>
>The best I have come up with so far is vars(), from which I can scan for
>instances of the relevant classes.
>
>However the name of the instance is returned as a string. How would I get
my
>hands on the actual instance from this in order to get at its instance so
as
>to print the data? Or is there a better way of going about what I need to
>do?
>
>
Here an example, which uses the built-in function getattr.
Is it this, what you need?
>>> class A:
def __init__(self,x,y):
self.one = x
self.two = y
>>> a = A(1,2)
>>> b = A(1001,1002)
>>> for name, instance in vars().items():
if isinstance(instance,A):
print name, instance.one, instance.two
a 1 2
b 1001 1002
>>> for name, instance in vars().items():
if isinstance(instance,A):
print name
for var in vars(instance):
print var, getattr(instance,var)
a
two 2
one 1
b
two 1002
one 1001
>>>
Regards, Gregor
>Thanks,
>Eddie.
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
More information about the Tutor
mailing list