Summary: In this tutorial, we will learn what __repr__
and __str__
are and what is the difference between them in Python.
__repr__ in Python
__repr__
is a reserved function in Python that returns the string representation of the object.
This string representation is such that when passed to eval()
, the object with the same value is produced.
It is invoked when we use the in-built repr()
function on the object or write the object’s name on the interactive Python console.
import datetime
today_date = datetime.datetime.now()
print(today_date) #2021-04-23 12:33:29.397901
print(repr(today_date)) #datetime.datetime(2021, 4, 23, 12, 33, 29, 397901)
As you can notice, the value of today_date
with and without repr()
are different.
If we pass the string returned from the repr()
to the eval()
function, we get the evaluated form of the datetime
object (i.e. value same as today_date
).
print(eval(repr(today_date))) #2021-04-23 12:33:29.397901
For the user-defined type such as class, we have to override the __repr__ method to return the appropriate string representation of the object.
Otherwise, Python by default will return the name of the type of the object together with additional information often including the name and address of the object.
Example 1: When not overriding the __repr__
class Car:
def __init__(self, name):
self.name = name
print(repr(Car("Lamborghini")))
Output: <__main__.Car object at 0x7f3b6ff00d00>
Example 2: When overriding the __repr__
class Car:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Car(%r)'%self.name
obj = Car("Lamborghini")
print(repr(obj))
Output: Car(‘Lamborghini’)
In the first example, we have not overridden the __repr__
function, so Python returns the default string representation as class’s name and address.
In the second example, we have successfully overridden the __repr__
function to return the appropriate string representation of the object.
Note the string that we are returning from the function. It is in such a format that it can be evaluated using the eval()
function.
class Car:
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Car(%r)'%self.name
def display(self):
print("Name: ",self.name)
#Car's object
obj = Car("Lamborghini")
#string representation of the object using repr()
string_obj = repr(obj)
#calling display() of the object using eval()
eval(string_obj+".display()")
Output: Name: Lamborghini
__str__ in Python
__str__
is a reserved function in Python that returns the readable form of the object in the string format.
It is invoked when we use the inbuilt str()
function on the object or output the object by using the print()
function.
Stack Overflow
str(object)
does not always attempt to return a string that is acceptable toeval()
; its goal is to return a printable string.
Example 1:
import datetime
today_date = datetime.datetime.now()
print(today_date) #2021-04-24 10:24:37.338077
print(str(today_date)) #2021-04-24 10:24:37.338077
Note the value of the today_date
with and without the str()
function is the same.
Example 2:
class Car:
def __init__(self, name):
self.name = name
def __str__(self):
return 'Car{name: %r}'%self.name
obj = Car("Lamborghini")
print(str(obj))
Output: Car{name: ‘Lamborghini’}
Note the __str__
function, unlike __repr__
we are returning the string representation of the object that is more readable and understandable.
Difference between __str__ and __repr__
The __repr__
function gets invoked when the repr()
method is used on the object, whereas __str__ is invoked when the str()
method is used on the object.
The __repr__
function acts as the fallback function when the __str__
function is not implemented.
For example, in this case, the output for both str()
and repr()
is returned from the __repr__
function:
class Car:
def __repr__(self):
return "__repr__ MyClass"
obj = Car()
print(str(obj))
print(repr(obj))
Output:
__repr__ MyClass
__repr__ MyClass
The final difference between the two is that, the __repr__
function tries to return a string representation of the object that can be evaluated using the eval()
method, whereas the same is not true for the __str__
.