Python › Magic Methods & Operator Overloading
What is the difference between __str__ and __repr__?
BeginnerAnswer
__str__ should return a readable, user-facing string (used by print() and str()), while __repr__ should return an unambiguous, ideally eval-able representation useful for debugging (used by the REPL and repr()). If __str__ is not defined, Python falls back to __repr__ for str() and print().
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point(x={self.x}, y={self.y})'
def __str__(self):
return f'({self.x}, {self.y})'
p = Point(1, 2)
print(str(p)) # (1, 2)
print(repr(p)) # Point(x=1, y=2)Real-world example In a debugging session, a list of custom objects printed in the console shows each item's __repr__, making it crucial to implement a clear, informative __repr__ for every domain model class.