What is the difference between __str__ and __repr__ in Python?
__str__ gives a readable description meant for users and is used by print() and str(). __repr__ gives an unambiguous description meant for developers, ideally looking like code that recreates the object. If only __repr__ exists, print falls back to it.
Explain it simply
A cricket scorecard on TV says "Kohli, 82 off 53". That is the friendly __str__. The official scorer's book lists "Player(name='Virat Kohli', runs=82, balls=53)", precise enough to rebuild the record. That is __repr__.
Containers such as lists show the repr of their items, which is why debugging output uses it.
Example
class Player:
def __init__(self, name, runs):
self.name = name
self.runs = runs
def __repr__(self):
return f"Player(name={self.name!r}, runs={self.runs})"
def __str__(self):
return f"{self.name} scored {self.runs}"
p = Player("Rohit", 101)
print(p) # Output: Rohit scored 101
print(repr(p)) # Output: Player(name='Rohit', runs=101)
print([p]) # Output: [Player(name='Rohit', runs=101)]
print(f"{p}") # Output: Rohit scored 101What to say in the interview
"__str__ is for end users and is called by print and str(); __repr__ is for developers, should be unambiguous, and is used in the REPL, in logs and inside containers. I always define __repr__ at minimum, because print falls back to it when __str__ is missing, but not the other way round."
Common mistakes
- Defining only
__str__and then seeing ugly<Player object at 0x...>inside lists.