First page Back Continue Last page Overview Graphics

__str__ and __repr__

>>> class A:

... def __str__(self):

... return "42"

...

>>> a = A()

>>> print(repr(a))

<__main__.A object at 0xb720a4cc>

>>> print(str(a))

42

>>> a

<__main__.A object at 0xb720a4cc>

>>> class A:

... def __repr__(self):

... return "42"

...

>>> a = A()

>>> print(repr(a))

42

>>> print(str(a))

42

>>> a

42

__str__ is always the right choice, if the output should be for the end user or in other words, if it should be nicely printed.

__repr__ on the other hand is used for the internal representation of an object. The output of __repr__ should be - if feasible - a string which can be parsed by the python interpreter.

The following should be true for an object "o": o == eval(repr(o))