all Python 3OOPfunction
__repr__
magic methods
The method repr(obj) and the console call: an unambiguous representation of the object for developers.
Syntax
def __repr__(self) -> str: ...
A good __repr__ looks like the expression that recreates the object: Point(1, 2). It also serves as the fallback __str__, which is why it is the one to define first. The built-in default prints <__main__.Point object at 0x…>, useless in both debugging and logs.
Examples
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x!r}, {self.y!r})'
p = Point(1, 2)
print(repr(p)) # → Point(1, 2)
print(p) # → Point(1, 2) — __str__ нет, взят __repr__
print(f'{p!r}') # → Point(1, 2)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy