Printable string for 'self'

Ben Cartwright bencvt at
Wed Mar 15 05:17:03 CET 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)

Not a direct answer to your question, but this may be what you want:
If you give class C a __repr__ method you can avoid the default <class
instance at address> string.

  >>> class C(object):
          def __init__(self, name):
     = name
          def __repr__(self):
              return '%s(%r)' % (self.__class__.__name__,
          def meth(self, y):
              print 'about to call %r.meth(%r)' % (self, y)

  >>> fred = C('Fred')
  >>> fred.meth(27)
  about to call C('Fred').meth(27)
  >>> def meth2(x, y):
          print 'about to call meth2(%r, %r)' % (x, y)

  >>> meth2(fred, 42)
  about to call meth2(C('Fred'), 42)

Of course, this doesn't tell you the name of the variable that points
to the instance.  For that (here's your direct answer), you will have
to go to the source:

  >>> import inspect
  >>> import linecache
  >>> def f(a, b):
          print 'function call from parent scope:'
          caller = inspect.currentframe().f_back
          filename = caller.f_code.co_filename
          line = linecache.getline(filename, caller.f_lineno)
          print '    ' + line.strip()
          return a*b

  >>> fred = 4
  >>> x = f(3, fred)
  function call from parent scope:
      x = f(3, fred)

But defining __repr__ is far easier and more common.


More information about the Python-list mailing list