Curriculum
In Python, the __repr__
method is a special method that is used to define a string representation of an object that can be used to recreate the object. This method is called when the object is passed to the repr()
function or when the object is evaluated in the Python shell. The __repr__
method should return a string that represents the object in a way that can be used to recreate the object.
Here’s an example of how the __repr__
method can be used in Python:
class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point({self.x}, {self.y})" p = Point(1, 2) print(repr(p)) # Output: "Point(1, 2)"
In this example, we define a Point
class with two attributes: x
and y
. We also define a __repr__
method that returns a string representation of the object that includes the Point
class name and the x
and y
attributes.
When we create a new Point
object and pass it to the repr()
function, the __repr__
method is called and generates a string representation of the object that includes the Point
class name and the x
and y
attributes. This allows us to recreate the Point
object by passing the output of repr()
to the eval()
function, like this:
p_str = repr(p) # "Point(1, 2)" p2 = eval(p_str) print(p2) # Output: "Point(1, 2)"
Note that the __repr__
method is not the same as the __str__
method, which is used to define a string representation of an object that is more general-purpose and should provide a human-readable output. The __repr__
method is used for more technical representation of the object that can be used to recreate it.