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)
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))
Note:
__str__()gives a short, readable text.__repr__()gives a more technical result, that looks like the code needed to recreate the object.