How to change default behaviour of a class?

Stefan Franke spamfranke at
Mon Aug 30 07:03:57 EDT 1999

On Mon, 30 Aug 1999 12:36:00 +0200, "Gerhard W. Gruber" <g.gruber at> wrote:

>How can I change what is printed when I use the statement "print class"?
>Usually this leads to an output like <class instance at 9aad60> but I
>rather want it to print variables contained in my class instead of the
>pointer adress.

>From your output I suppose meant "print instance" and "variables contained 
in my instance".

There are two special methods __repr__ and __str__, which can be used
to customize the classes string pepresentation. The print statement 
tries to call __str__. If __str__ is not defined it uses __repr__ or
the default representation otherwise.

for some documentation. 

A short example:

>>> class C:
...   def __repr__(self):
...     return repr (self.__dict__)
>>> c = C()
>>> c.a = 1
>>> c.b = "My String"
>>> c
{'b': 'My String', 'a': 1}


More information about the Python-list mailing list