String Representation Dunders: `__str__` vs `__repr__`
`__str__` returns a readable string for end-users (`print()`). `__repr__` returns an unambiguous debugging representation for developers.
class User:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return f"User(name={self.name!r})"
u = User("Alice")
print(str(u)) # Alice
print(repr(u)) # User(name='Alice')
# 4. String Representation Dunders: `__str__` vs `__repr__` `__str__` returns a readable string for end-users (`print()`). `__repr__` returns an unambiguous debugging representation for developers: ```python class User: def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return f"User(name={self.name!r})" u = User("Alice") print(str(u)) # Alice print(repr(u)) # User(name='Alice') ``` If you only implement one, implement `__repr__`. When `__str__` is missing, Python automatically falls back to `__repr__` for standard `print()` calls.