overloading print behavior

Steven Taschuk staschuk at telusplanet.net
Mon Apr 28 01:32:07 EDT 2003


Quoth Cere Davis:
  [...]
> When I:
> 
> print st
> 
> I get:
> 
> ['abc', <__main__.C instance at 0x40288fac>]
> 
> Which is what I expect,  but I would like it if print or perhaps the 
> str() coercion that is happening behind the scenes would walk through my 
> C instance
> and resolve the name/value paris within the C class and print the 
> values.  [...]

Actually it's repr() and not str() in the above example, as I will
describe below.

To specify str() conversion (which also applies for print
statements) for your class, you need to write a __str__ method:

    class Foo(object):
        def __init__(self, n):
            self.n = n
        def __str__(self):
            return 'Foo with n = %s' % self.n

To specify repr() conversion, you need to write a __repr__ method:

        def __repr__(self):
            return 'Foo(%r)' % self.n

The difference between str and repr is described in the docs:
    <http://www.python.org/doc/2.2.2/ref/customization.html>
(This part of the documentation is presently the subject of some
scrutiny here; some feel it is unclear, misleading, wrong.  The
discussion is in this thread:
    <http://groups.google.com/groups?th=24b817d49ec3a59b>
    (or <news:uw1i4nqpl33h.1l3wpteil4jb0.dlg at 40tude.net> et seq.)
If the docs leave you in doubt about whether you should be writing
a __str__ method or a __repr__, have a look through those posts.
You might want to skip the digression about orbital mechanics.)

The other thing to know is that, when you print a list (or dict
or tuple) containing your objects, those objects will be printed
by repr conversion, not by str conversion.  (Lists etc. actually
have no __str__, so Python falls back to the list's __repr__,
which in turn uses the __repr__ of the list's elements.)  There
are those whom this behaviour annoys; see the aforementioned
thread for some discussion (and an explanation of why it's the
way it is).

If you do want to include all the attributes of your objects in
the repr of those objects (this would not really be appropriate
for str, imho), then you could do it this way:

    class Foo(object):
        def __init__(self, a, b):
            self.a = a
            self.b = b
        def __repr__(self):
            pairs = ['%s = %r' % (name, value)
                for name, value in self.__dict__.items()]
            return '<a Foo with ' + ', '.join(pairs) + '>'

Then, for example:

    >>> Foo(3, 4)
    <a Foo with a = 3, b = 4>

-- 
Steven Taschuk                            staschuk at telusplanet.net
"Our analysis begins with two outrageous benchmarks."
  -- Clinger et al., "Implementation strategies for continuations"





More information about the Python-list mailing list