/  Technology   /  What is the difference between __str__ and __repr__?

What is the difference between __str__ and __repr__?

In Python, the object class has a number of magic methods(methods that start and end with double underscores). We never call these methods directly. A corresponding built-in function calls one of these magic methods internally. Let’s stick to str and repr in this article. So the built-in str() function invokes the  __str__() magic method and the built-in repr() function invokes the __repr__() magic method. 

Both these functions give the string representation of a string.

Now let’s see what’s the use of two different functions for the same functionality. Look at the example below.

 

We have passed a string ‘Python with i2tutorials’ to a variable a. We can see that both these functions, when called, are returning the corresponding string but the repr() function adds quotes to it. This is the formal representation of a string whereas str() gives the informal representation of a string.

The formal representation adds a lot of value to the information and a lot of detail which is much helpful for developers while debugging.

The informal representation aims at increasing the readability of the output for the users. We can understand this by the following example.

Let’s make these functions work for our own defined class, class A and an object a.

Note: We must never use these functions directly, we should always use the str() and repr() functions, which will call the underlying __str__() and __repr__() functions.

 

Leave a comment