Python __repr__() Method
The __repr__() Method
While __str__() controls the readable, user-facing text shown when you print an object, __repr__() controls a more technical representation, meant for developers.
Example
Use __repr__() to describe the object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
p1 = Person("Tobias", 25)
print(p1)
Try it Yourself »
Note: This class has no __str__() method, so Python falls back to __repr__() when the object is printed.
__str__() vs __repr__()
When a class defines both __str__() and __repr__(), print() uses __str__(), while the built-in repr() function always uses __repr__():
Example
Define both methods, and compare what each one produces:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age})"
p1 = Person("Emil", 36)
print(p1)
print(repr(p1))
Try it Yourself »
Note: __str__() gives a short, readable text. __repr__() gives a more technical result, that looks like the code needed to recreate the object.