Quick Earn Money

What is the difference between __str__ and __repr__?

 

Certainly! Here's a more detailed explanation with examples to illustrate the difference between __str__ and __repr__:

  1. __str__ Method: The __str__ method is used to define a human-readable string representation of an object. It should be clear, informative, and suitable for end-users. This method is called by the str() function and automatically when using print().

Example:

python
class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"Point({self.x}, {self.y})" p = Point(3, 5) print(str(p)) # Output: Point(3, 5) print(p) # Output: Point(3, 5) - Due to the __str__ method
  1. __repr__ Method: The __repr__ method is used to define an unambiguous and developer-friendly string representation of an object. It should ideally return a string that, when passed to the eval() function, would recreate the object.

Example:

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(3, 5) print(repr(p)) # Output: Point(3, 5)

In this example, __str__ provides a human-readable representation of the Point object, while __repr__ provides an unambiguous string that could be used to recreate the object.

You can see the difference more clearly when using functions like str() and repr() explicitly:

python
p = Point(3, 5) print(str(p)) # Output: Point(3, 5) print(repr(p)) # Output: Point(3, 5)

In summary, __str__ is for user-friendly display, while __repr__ is for providing a clear and unambiguous representation of an object for developers and debugging purposes.

Comments