__repr__
__repr__ returns an unambiguous text form of an object for programmers; __str__ returns a friendly one for readers, used by print.
In more detail
Without __repr__, an object shows as something like <Point object at 0x...>, which helps nobody in the shell or a debugger. If you only define one, define __repr__; print falls back to it.
Example
def __repr__(self):
return f"Point({self.x}, {self.y})"Related terms
- dunder method — A method whose name starts and ends with two underscores, such as __init__ or __len__, which Python calls for you to implement built-in behaviour.
- print() — The built-in function that writes values to the screen, separated by spaces and followed by a newline.
- dataclass — A class decorated with @dataclass from the dataclasses module, which writes __init__, __repr__ and __eq__ for you from a list of annotated fields.
Taught in
- Raising, And Writing Your Own Exception — Hands-on Python: Complete Video Course & Book
- Dunder Methods, And Making Objects Pythonic — Hands-on Python: Complete Video Course & Book
- Paths And Files The Modern Way — Hands-on Python: Complete Video Course & Book