Understanding __str__ vs __repr__
Published:
• Last updated:
• By Jeferson Peter
Python
Imagine you created a custom class in Python and want to print objects in a readable way.
Should you implement__str__
or__repr__
? Let’s see the difference.
str: user-friendly representation
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
p = Person("Alice", 30)
print(p)
# Alice, 30 years old
__str__
is what print()
shows — aimed at end users.
repr: unambiguous representation
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
p = Person("Alice", 30)
print(repr(p))
# Person(name='Alice', age=30)
__repr__
is used for developers/debugging. Ideally, it should look like valid Python code.
Both together
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age} years old"
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
p = Person("Bob", 25)
print(p) # str
print(repr(p)) # repr
Conclusion
- Use
__str__
for user-friendly display (e.g., in UI, reports). - Use
__repr__
for debugging and dev tools. - If only one is defined,
__repr__
is the safer choice, since it’s used as a fallback.