overloading print behavior

Alexander Schmolck a.schmolck at gmx.net
Mon Apr 28 06:54:25 CEST 2003

Cere Davis <cere at u.washington.edu> writes:

> So I have a function like:
> class C:
>     def __init__(self):
>        self.a="asdf"
>        self.b="123"
> c=C()
> st=["abc",c]
> 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.
> Something like:
> print st
>  > 'abc',<C instance>['a=asdf','b=123']

> Could someone enlighten me on this simple concept?


class C:
    def __init__(self):
    def __repr__(self):
        return "<%s instance with a=%r, b=%r>" % (self.__class__,
                                                  self.a, self.b)

>>> C()
<__main__.C instance with a='asdf', b='123'>

The place to look these things up is the language reference (all "magical"
methods used to customize instance behavior are listed there).


More information about the Python-list mailing list