How to Call __repr__() in Python

In Python, special or magic methods provide a means of changing or altering built-in behaviors. Some examples of special methods include: __init__, __del__, __eq__, __ne__, and among others.

One noteworthy method is the __repr__() method which provides a developer-controlled way to represent an object for debugging and logging, and also at the interactive prompt. This tutorial will demonstrate how you can call the __repr__() method in Python.

Step 1: Defining the object class

To showcase the __repr__() method, let’s create a Person object class with first name, last name, and age attributes.

Step 2: Implementing the __repr__() method

We then add the __repr__() method to our Person class. This method will return a printable representation of the object.

Step 3: Instantiating the object and printing its representation

Now, instantiate an object of the Person class and print it.

The output would be:

Person(John, Doe, 30)    

Full Code

Conclusion

In Python, calling the __repr__() method can be very handy in debugging as it provides a human-readable output of an object. You can customize it based on your needs to get the most useful information out of your objects.