Introspection Class/Instance Name

Duncan Booth duncan.booth at invalid.invalid
Wed Apr 26 04:09:20 EDT 2006


*binarystar* wrote:

> class Bollocks:
>      
>      def __init__( self ):
>           
>           print self.__method_that_returns_class_name__()
>           print self.__method_that_returns_instance_name__()
> 
> 
> instance_of_bollocks     = Bollocks()
> 
> # Which outputs
> 
> 'Bollocks'
> 'instance_of_bollocks'
> 

>>> class Bollocks(object):
    def name_of_instance(self):
        return "self"

    
>>> instance_of_bollocks = Bollocks()
>>> print instance_of_bollocks.__class__.__name__
Bollocks
>>> print instance_of_bollocks.name_of_instance()
self
>>> 

At the time when the method is called, 'self' is a perfectly valid name for 
the instance. Seriously though, how do you expect a method to decide if you 
do:

>>> another_name = instance_of_bollocks
>>> print another_name.name_of_instance()
??? which name should appear here ???
>>> more = [another_name]*5
>>> print more[2]
??? and what name here ???

and did you want a global name, or a local variable from some function and 
if so which function and at which stack level?

Python does actually give you sufficient introspection to do this, but you 
have to write some fairly complex code to iterate through the namespaces 
you are interested in searching for the object.

A much more reasonable solution is to give your object a name attribute:

>>> class Bollocks(object):
    def __init__(self, name):
        self.name = name

        
>>> instance_of_bollocks = Bollocks('Archimedes')
>>> print instance_of_bollocks.name
Archimedes



More information about the Python-list mailing list