🐍 Python
Intermediate
What is Python's __str__ and __repr__ methods?
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.