get instance name inside of member function

Peter Hansen peter at engcorp.com
Thu Jan 9 10:06:36 EST 2003


Ralf Oberländer wrote:
> 
> Hi gurus,
> 
> is it possible to get the name of the instance inside a member function:

Basically, no.  The question is broken though: in Python there is
not _the_ name, only _a_ name.  An object cannot find "the" name 
bound to it because there can be many.

> class a:
>      def inst_name():
>          pass
> 
> inst=a
> 
> so that
> 
> inst.inst_name()
> 
> results in the string "inst"
> 
> I need it for logging

Good that you provided your actual goal; most people do not.

For logging, it's normal to supply "the" name to the initializer
when you create the instance, and use that in logging.

class A:   # also standard style to use Capitalized name for a class
    def __init__(self, name):
        self.name = name
    def inst_name():
        return self.name

inst = A('anA')
inst.inst_name()  

# returns 'anA'

-Peter




More information about the Python-list mailing list