Both customize how an object becomes text, but they target different audiences.
__repr__
- Unambiguous, developer-oriented representation.
- Ideal goal: string that could recreate the object (
eval-able when practical). - Used by the interactive console and when containers print elements.
__str__
- Readable, user-facing description.
- Used by
str(obj)andprint(obj). - If
__str__is missing, Python falls back to__repr__.
class User:
def __init__(self, user_id: int, name: str):
self.user_id = user_id
self.name = name
def __repr__(self) -> str:
return f"User(user_id={self.user_id!r}, name={self.name!r})"
def __str__(self) -> str:
return f"{self.name} (#{self.user_id})"
u = User(7, "Asha")
print(str(u)) # Asha (#7)
print(repr(u)) # User(user_id=7, name='Asha')
print([u]) # uses repr inside containersInterview mnemonic: repr for developers/debugging; str for humans/display.