[Tutor] Accessing the name of an instance variable

Gregor Lingl glingl at aon.at
Sun Nov 16 07:26:05 EST 2003


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