all Python 3OOPfunction
__str__
magic methods
The method str(obj), print() and f-strings call: a readable representation of the object for people.
Syntax
def __str__(self) -> str: ...
Without __str__, str() falls back to __repr__ — so a single __repr__ is enough, and __str__ is added only when users need a different, friendlier form. Containers print their items with repr, not str: print([obj]) shows __repr__.
Examples
class Temp:
def __init__(self, c):
self.c = c
def __str__(self):
return f'{self.c} °C'
def __repr__(self):
return f'Temp({self.c})'
t = Temp(21)
print(t) # → 21 °C
print(f'Сейчас {t}') # → Сейчас 21 °C
print([t]) # → [Temp(21)] — элементы списка печатаются через repr
See also
Open in the full glossarydocs.python.orgReport an inaccuracy