repr in Python
How to use __repr__ in Python to create a human-readable representation of an object. This blog post will explore the Python magic method, Let’s make a simple class Person without a Without Let’s create a simple class Person with a We use The print statement searches for For example: When writing a To reconstruct the object from the repr output, make sure to add all the constructors ( It’s easy to recreate another object of the same class. Dynamic repr methods: You can create dynamic Inheritance and repr: Use class inheritance to create custom Understanding Python’s Introduction
__repr__
. This method is useful and even necessary to display a human-readable representation of an object. We’ll start with the basics and work up to more advanced concepts. What is
__repr__
?__repr__
is a magic method in Python that allows us to define a human-readable representation of an object.repr()
function on an object, Python looks for a __repr__
method within that object’s class definition. If it finds one, it returns the result of that method; otherwise, it provides a default representation.__repr__
and __str__
: while __repr__
is designed to provide an unambiguous representation of the object (which can ideally be used to recreate it), __str__
is meant to return a more user-friendly string representation. We will discuss more on this. Creating a primary
__repr__
method__repr__
method.
=
=
=
# Output: <__main__.Person object at 0x7f8893925df0>
__repr__
method, the object points to the memory address.__repr__
method.
=
=
return f
=
# Output: Person('Soumendra', 30)
__repr__
method returns a string that looks like the object’s constructor, making it easy to understand and recreate the object if needed.type(self).__name__
is a best practice to use rather than hard coding the class name.
__str__
and __repr__
__str__
method for more user-friendly logs for humans to read.__str__
method first in a class, otherwise it goes for __repr__
method.
=
=
return f
return f
=
# Output: A Person object of name, Soumendra and age, 30.
# Output: Person('Soumendra', 30)
How to write effective
__repr__
methods__repr__
method, include all relevant object attributes, and ensure the output is unambiguous. This allows other developers to quickly understand the object’s state and reconstruct it if necessary.__init__
) attributes to the __repr__
method. Therefore, it becomes easy to replicate the object. For example, in the above Person
class example:>>> =
>>>
>>> =
>>>
__repr__
methods using class attributes. For example:
=
=
return
__repr__
methods that leverage the parent class’s __repr__
implementation:
=
return f
Conclusion
__repr__
method is essential for creating informative and unambiguous object representations. By implementing custom __repr__
methods and leveraging advanced techniques, you can improve the clarity and usability of your Python code.