[Tutor] Accessing the name of an instance variable

Gonçalo Rodrigues op73418 at mail.telepac.pt
Sun Nov 16 09:32:52 EST 2003


On Sun, 16 Nov 2003 13:53:41 -0000, you wrote:

>Thanks Goncalo. I have sorted something out with the below, but it won't
>work from another module (see further below).
>
>The purpose is to print a description of the objects created for third party
>users of my code.
>
>Eddie.
>
>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
>
>#pp.pprint(read_code_helper.helper.description(self))
>                        print self.one, self.two
>
>if __name__ == '__main__' :
>
>    a = A(1,2)
>    b = A(1001,1002)
>
>    a.describe()
>    b.describe()
>
>
>import get_name
>
>a = get_name.A(1,2)
>
>a.describe() #dosen't pick up the name, presumably a scoping issue.
>
>

Yes, I forgot to add that globals is really only *module-level*
globals.

Stil,l I don't grok why do you have to mess up with vars or globals
(or whatever) to, in your own words, "print a description of the
objects created for third party users of my code." As a rule of thumb,
Python classes that want to display a string-like description useful
for debugging implement a __repr__ method, e.g.

>>> class A(object):
... 	def __init__(self, x, y):
... 		self.one = x
... 		self.two = y
... 	def __repr__(self):
... 		return "%s(%r, %r)" % (self.__class__.__name__,
self.one, self.two)
... 	
>>> a = A(1, 2)
>>> a
A(1, 2)
>>> 

When at the interative prompt, a variable name will simply display
repr(<variable name>), which in its turn calls __repr__ for classes
that implement it.

The way I coded __repr__ as the advantage of allowing the sometimes
useful idiom:
>>> eval(repr(a))
A(1, 2)
>>> 

:-)

With my best regards,
G. Rodrigues

P.S: Don't want to be a pain but could you please do:

1. Reply *also* to the Tutor list. That way everybody can learn and
chime in. And even correct me when I'm wrong :-)

2. Don't top-post, it makes harder to follow the threads.



More information about the Tutor mailing list