__str__ and __repr__

The special methods that give an object its readable form and its developer form.

In more detail

print(), str() and f-strings use __str__; repr(), the interactive prompt and the display of objects inside a list use __repr__. The default repr shows the class name and a memory address. If a class defines only __repr__, str() falls back to it.

Example

class M:
    def __str__(self): return 'm'
    def __repr__(self): return 'M()'
print(M(), [M()])   # m [M()]

Related terms

Taught in

References

Certification courses