What’s the difference between “__str__” and “__repr__” in python

Sachinjose
2 min readJul 2, 2021
Photo by Surface on Unsplash

The goal of __repr__is to be unambiguous and __str__ is to be readable. By the end of this article, you may be able to understand how it differs.

According to official python documentation,__repr__ a built-in function is used to compute an object's “official” string reputation, while __str__ is a built-in function that computes the “informal” string representations of an object.

Let’s try to create a Student class that accepts two parameters as input. After initializing the class, if you inspect the object, all you get is a string containing the class name and the id of the object instance.

Let's try to add a dunder method __str__ with string to return. When we try to print the class, we will get the string returned from the method. But when you inspect the class, it will return the address of the object.

Now we will try to add __repr__ the method with string to return. When we print or inspect the class, we will get the string returned from the repr method.

If we include both __repr__ and __str__ inside the class, when we use the print statement __str__ will be called and for other __repr__ will be returned

Conclusion

In short, when we use a print statement, it checks for the __str__ method. If it is not available, then it checks for the __repr__ method.

Both __str__() and __repr__( ) are used to compute a string representation for objects under

__repr__ is for developers (purpose of debugging and development).

__str__ It is for customers(creating human-readable output).

--

--