__repr__
method
The __repr__
special method is called by the repr
built-in to get the string representation of the object for inspection.
Without a custom __repr__
, Pythonโs console would display a Vector
instance <Vector object at 0x10e100070>
.
The string returned by __repr__
should be unambiguous and, if possible, match the source code necessary to re-create the represented object. E.g. Vector(1, 2)
instead of Vector('1', '2')
, if parameters should be integers, and not strings.
For that, the good practice is to use !r
conversion flag:
__repr__
implementation should be prioritized over __str__
.
__str__
method
In contrast, __str__
is called by the str()
built-in and implicitly used by the print
function. It should return a string suitable for display to end users.
Sometimes the string returned by __repr__
is already user-friendly. In that case you donโt need to code __str__
because the implementation inherited from the object
class calls __repr__
as a fallback. But not vice versa.
__repr__
vs __str__
https://stackoverflow.com/questions/1436703/what-is-the-difference-between-str-and-repr