First page Back Continue Last page Overview Graphics

__str__ and __repr__ Methods

>>> languages = ["Python", "Java", "C++", "Perl"]

>>> str(languages)

"['Python', 'Java', 'C++', 'Perl']"

>>>

>>> s = "1st line\n2ndline"

>>> str(s)

'1st line\n2ndline'

>>> repr(s)

"'1st line\\n2ndline'"

If the functions str or repr are applied to an object, Python looks for the __str__ or __repr__ in the class definition. Python uses the Default output for str or repr if __str__ or __repr__ are not defined.

>>> class A:

... pass

...

>>> a = A()

>>> print(a)

<__main__.A object at 0xb720a64c>

>>> print(repr(a))

<__main__.A object at 0xb720a64c>

>>> print(str(a))

<__main__.A object at 0xb720a64c>