Printable string for 'self'

Michael Spencer mahs at telcopartners.com
Tue Mar 14 21:13:52 EST 2006


Don Taylor wrote:
> Is there a way to discover the original string form of the instance that 
> is represented by self in a method?
> 
> For example, if I have:
> 
> 	fred = C()
> 	fred.meth(27)
> 
> then I would like meth to be able to print something like:
> 
> 	about to call meth(fred, 27) or
> 	about to call fred.meth(27)
> 
> instead of:
> 
> 	about to call meth(<__main__.C instance at 0x00A9D238>, 27)
> 
> Thanks in advance,
> 
> Don.
> 
In general, this requires exhaustive search of name bindings e.g.,:

 >>> def get_names_of(obj, ns):
...     return [name for name, value in ns.iteritems() if value is obj]
...
 >>> class A(object):
...     def global_names_bound_to_me(self):
...         return get_names_of(self, globals())
...
 >>> a = A()
 >>> a.global_names_bound_to_me()
['a']
 >>> b = a
 >>> a.global_names_bound_to_me()
['a', 'b']
 >>>

HTH
Michael




More information about the Python-list mailing list