🐍 Python Intermediate

What is Python's __str__ and __repr__ methods?

Why Interviewers Ask This

This question targets practical, hands-on experience with Python. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Both are magic methods for string representation of objects. __repr__ should return an unambiguous representation — ideally one that could recreate the object: def __repr__(self): return f"User(name={self.name!r}, age={self.age})". It is called by repr(obj), in the REPL, and by containers (list elements shown in repr). __str__ should return a human-readable string: def __str__(self): return f"{self.name} (age {self.age})". Called by str(obj), print(obj), and f-strings (f"{obj}"). If only __repr__ is defined, it is used as fallback for __str__. Rule of thumb: implement __repr__ always; add __str__ only when you want a friendlier display format different from repr.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Python experience.