defining __repr__

Steve Holden steve at holdenweb.com
Mon Sep 12 15:21:53 EDT 2005


sven wrote:
> hi list,
> i'd like to define __repr__ in a class to return the standardrepr
> a la "<__main__.A instance at 0x015B3DA0>"
> plus additional information.
> how would i have to do that?
> how to get the standardrepr after i've defined __repr__?
> 
> sven.
> 
It's relatively easy for new-style (type-based) classes:

  >>> class C(object):
  ...   def __repr__(self):
  ...     return "Extra stuff then\n%s" % super(C, self).__repr__()
  ...
  >>> i = C()
  >>> repr(i)
'Extra stuff then\n<__main__.C object at 0x4e0b6c>'
  >>>

Not immediately clear how to extend that to old-style objects since they 
aren't as cooperative in making their superclass as readily available.

Unless your needs are specifically for old-style classes I'd suggest 
using new-style classes.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC             http://www.holdenweb.com/




More information about the Python-list mailing list