Default printing behavior for classes

Michael P. Reilly arcege at shore.net
Thu Jun 24 19:43:56 CEST 1999


Ben Glazer <glazer at scicomp.com> wrote:
: I'm looking for a way to set default printing behavior for a class I've
: defined.  Lists are printed in a certain format by default.  I'd like to
: be able to define this for any type of class.  It'd be really nice if
: there were something I could include in my class definition, e.g.

:  class Board:
:      def __init__(self, width=2, height=4, length=20):
:          self.width = width
:          self.height = height
:          self.length = length

:      def __print__:
:          print "[%s,%s,%s]" % (width,height,length)

: such that

:  b = Board(8,8,2)
:  print b

: would print "[8,8,2]".

: Is there anything in Python that encapsulates this functionality, or
: should I resign this desire to a feature req for Python 2.0?

There are two such things: the result from repr(object) and from
str(object).  You can create your own versions by creating the methods
"__repr__" and "__str__" respectively.  Both are to return a string.

The more general is the output of repr(), if there is no method to
output str(), then repr() is used.  The "print" statement uses str(),
containers (lists, dictionaries, etc.) and string conversion (`...`)
both use repr().

Why are there two such functions?  Taking just one simple example, look
at the output of a Python string:

  >>> a = 'Hi\tBen\n'
  >>> print a
  Hi      Ben

  >>> print str(a)
  Hi      Ben

  >>> print repr(a)
  'Hi\tBen\n'
  >>>

With the str() function it is difficult to see the special characters.
The repr() is used to show the internal representation of the object,
not the human-readable "pretty" representation.

Preferably, the result of repr() is something that can be called from
eval to recreate the object.

Since printing tuples, lists and dictionaries isn't generally "human
friendly" and more for use with eval(), repr() is used to print the
contained objects.

So for your class, you could write something like:

  class Board:
    def __init__(self, width=2, height=4, length=20):
      self.width = width
      self.height = height
      self.length = length
    def __str__(self):
      return '[%d, %d, %d]' % (self.width, self,height, self.length)
    def __repr__(self):
      return '%s(%d, %d, %d)' % (
        self.__class__.__name__,  # the instance class name
        self.width, self.height, self.length
      )

>>> print b
[8, 8, 2]
>>> print `b`
Board(8, 8, 2)
>>> b
Board(8, 8, 2)
>>> print 'The board is %s.' % b
The board is [8, 8, 2].
>>>

For more information, read the Python Language Reference manual.
(http://www.python.org/doc/current/ref/customization.html#l2h-288)

  -Arcege





More information about the Python-list mailing list