Intermediate LevelPython
What is the difference between __str__() and __repr__() dunder methods for object string representation?
❓ Interview Prompt: Compare `__str__()` (user-friendly display string) vs `__repr__()` (unambiguous developer debugging representation).
1. '__repr__(self)' (Developer Inspection):
•
Returns an unambiguous, developer-focused string representation (ideally executable code like 'Point(x=1, y=2)').
•
Used by interactive shells, loggers, and debugging tools ('repr(obj)').
2. '__str__(self)' (User Display):
•
Returns a clean, readable string intended for end-user UI display ('str(obj)' or 'print(obj)').
•
If '__str__' is not defined, Python automatically falls back to '__repr__'!
Code Implementation Example
python
class User:
def __init__(self, name, id):
self.name = name
self.id = id
def __repr__(self):
return f'User(name={self.name!r}, id={self.id})'
def __str__(self):
return f'User {self.name} (#{self.id})'
u = User('Alice', 101)
print(str(u)) # Output: User Alice (#101)
print(repr(u)) # Output: User(name='Alice', id=101)💡Implementing __str__ for end users and __repr__ for developers.
🎯 Interview Key Takeaway
Always implement __repr__ first on custom classes to ensure unambiguous debugging output.
#__repr__#__str__#Dunder Methods#Debugging#Intermediate
Back to all Python Questions→