Back
+15 XP
Concept

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')

# 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.

Checkpoint

Which dunder method should ideally output valid Python code to recreate the object?

Practice

Implement `__repr__` on class `Coord(x, y)` returning `f"Coord({self.x}, {self.y})"`. Instantiate `c = Coord(3, 4)` and print `repr(c)`.

Terminal
01
Tap code blocks below to assemble
Available Blocks