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.
1 2 3 4 5 |
class Person: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age |
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.
1 2 3 4 5 6 7 8 |
class Person: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def __repr__(self): return f'Person({self.first_name}, {self.last_name}, {self.age})' |
Step 3: Instantiating the object and printing its representation
Now, instantiate an object of the Person class and print it.
1 2 |
person1 = Person('John', 'Doe', 30) print(person1) |
The output would be:
Person(John, Doe, 30)
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 |
class Person: def __init__(self, first_name, last_name, age): self.first_name = first_name self.last_name = last_name self.age = age def __repr__(self): return f'Person({self.first_name}, {self.last_name}, {self.age})' person1 = Person('John', 'Doe', 30) print(person1) |
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.