[Tutor] Accessing the name of an instance variable

Alan Gauld alan.gauld at blueyonder.co.uk
Sun Nov 16 12:37:34 EST 2003


> The purpose is to print a description of the objects 
> created for third party users of my code.

Just to make sure we aren't going into overkill here...

If you have provided a doc string for your class that 
names the objects variables then your users can just 
print the doc string and use that to reference the 
values directly. [Printing the variable name in Python 
is usually a pretty pointless exercise since it's only 
a reference which you either know or don't need.]

However, assuming you really do need this level of 
introspection...

This could be made into a mixin class:

>class A:
>    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


This can now be used as a superclass of any other class 
that you need to describe:

#-----------
class B(A):
    ''' Class B, inherits A
    Class is initialised by two values x and y.
    Can be described using describe()'''
    
    def __init__(self,x,y):
        self.one = x
        self.two = y


b = B(1,2)
b.describe()
print '########### Using doc string to explore #######'
print b.__doc__
print 'x,y = ',b.x,b.y
#------------

Which produces the following output:

Describing
A
B
__builtins__
b
Description of b
__name__
__doc__
########### Using doc string to explore #######
 Class B, inherits A
    Class is initialised by two values x and y.
    Can be described using describe()
x,y =  1 2



Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list