Python

The__repr__ in Python

The __repr__() method of Python yields a textual or string depiction of an entity or an object. This process is termed whenever the entity’s repr() method is invoked. You can say that the “repr” method and “__repr__” can be used interchangeably for the same purpose. The text reverted must be a proper Python phrase that would be castoff to reassemble the entity if feasible. A “__str__” function of python does the same, but there is a slight difference between both the functions. The __str__ method is designed to produce a human-readable version, useful for tracking or displaying object information. The __repr__ method, on the other hand, is designed to provide an “official” textual image of the object that may be used to recreate it. We’ll focus on both key Python entity methods in our article today. Let’s have a fresh start.

Example 01

Open the python tool on your system, i.e., we are using Spyder 3 here. We will be taking a look at the simple repr method first. We have started our code by initializing a string variable with a string sentence as a value. The print function is used to print the string representation of the console’s variable “string” value. For this, we have utilized the “repr” method and taken string as an argument in it. After that, we applied the “repr” function on some mathematical expressions and tried to print it via the same function, “print.” Let’s take a glance at the output now.

string = 'Hy! I am John'
print (repr(string))
print (repr(5.0/11.0))

In the output shown below, you can see that the repr method shows the string representation of both the string value and the mathematical expression calculation.

Example 02

Let’s take a deeper glance at the “repr” and “Str” functions to clear the difference between both. This time, we have been applying these string representation methods on python’s date and time functions. To get the date and time in our code, we have first imported the DateTime module of python via the “import” keyword. So, we have to use the “now()” function with the DateTime class in the code to get the current date and time via its package and save the current timestamp in the “td” variable. Now, two print functions are used to print the current date and time in a string format using the “__str__” and “__repr__” function on the variable object “td.” Code has been saved and is ready to be executed.

import datetime
td = datetime.datetime.now()
print(td.__str__())
print(td.__repr__())

On running this code, we have got two different string results. The first result is generated by the “__str__” method and is quite understandable. While the other is generated by using the “__repr__” method and is quite difficult for us to understand.

Example 03

Let’s have a last but not the least example of this article. We have been using a user-defined Test class in our code. This class defines and implements its constructor function to save the “name” and “salary” in two different variables, v1 and v2. An object named “val” is created to pass the two values for the “name” and “salary” variable to the test function constructor. The creation of an object “val” causes the constructor of the test class to run automatically. The “__str__” and “__repr__” method is called using the object “val” separately and printing out the results. Both functions got nothing as the object “Val” was just created and did not value it. It might not respond to us the way we want it. Let’s check it.

class Test:
    def __init__(self, name, salary):
        self.v1 = name
        self.v2 = salary
val = Test('John', 50000)
print(val.__str__())
print(val.__repr__())

Here, both functions’ default carrying out is entire of no use. Let’s implement both functions now.

So, after the constructor within the class, we have implemented both the “__str__” and “__repr__” methods separately, returning the string format of a text. It also returns the values assigned to the constructor to the calling thread, i.e., the “val” object. Let’s save the newly updated python code first to see its results.

class Test:
    def __init__(self, name, salary):
        self.v1 = name
        self.v2 = salary
    def __str__(self):
        return f'User name is {self.v1} and his/her salary is {self.v2}'
    def __repr__(self):
        return f'User(name={self.v1}, salary={self.v2})'
val = Test('John', 50000)
print(val.__str__())
print(val.__repr__())

print(val.__repr__())

The first output is caused by the “__str__” method and is quite understandable. The other output is understandable but not as much as the “__str__” function output.

Conclusion

This article is all about using the “__repr__” method in python code. We have also discussed the “__str__” method used in this article to compare differences between functions. It would also make you understand the “__repr__” method more clearly. We eagerly hope that this article will be best for our users for help in python.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content