get instance name inside of member function
Duncan Booth
duncan at NOSPAMrcp.co.uk
Thu Jan 9 09:48:52 EST 2003
Ralf Oberländer <ralf.oberlaender at emsys.de> wrote in
news:3E1D869F.2050809 at emsys.de:
> is it possible to get the name of the instance inside a member function:
>
> class a:
> def inst_name():
Or even:
def inst_name(self):
> pass
>
> inst=a
Did you mean:
inst = a()
>
> so that
>
> inst.inst_name()
>
> results in the string "inst"
>
Consider:
inst2 = inst1 = a()
What do you want inst2.inst_name() to return, inst1 or inst2?
What do you want a().inst_name() to return?
The problem is your instance could be bound to many names or none.
If you know it is bound to a global in a particular module you could search
that module's globals to find one that is the same as 'self'. You could
even search all modules for globals bound to the instance.
If you want the particular binding used in the call, or a local name then
you would have to crawl back up the stack and pull apart the bytecode.
Of course if you simply want *any* of the names bound to the instance then
this does the trick (but somehow I don't think it helps):
def inst_name(self):
return "self"
> I need it for logging
The traditional way to do this would be:
class a:
def __init__(self, name):
self.name = name
and just create each instance with a unique name. Yes, I know this means
you have to type the name twice.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list