Python __repr__
In Python, the __repr__
method is a special method used to provide a string representation of an object. It is typically used for debugging and displaying information about the object in a concise and human-readable format.
The __repr__
method should return a string that is a valid Python expression that could be used to recreate the object. It is often used in combination with the __str__
method, which is used to provide a more user-friendly string representation of the object.
Here is an example of a class that defines the __repr__
method:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
point = Point(3, 4)
print(point) # Output: Point(3, 4)
In this example, the __repr__
method returns a string that represents the Point
object with its x
and y
coordinates.
It is important to note that the __repr__
method should always return a string that accurately represents the object. The __str__
method, on the other hand, allows for a more customized and user-friendly representation of the object.