Artificial Intelligence
Please fill the required field.

explain the difference between __str__ method and __repr__ method in python with example


In Python, both the `__str__` and `__repr__` methods are used to define string representations of an object, but they serve different purposes and are intended for different audiences. ### `__str__` Method: - The `__str__` method is intended to provide a "nice" or user-friendly string representation of an object. This is what is returned when you use the `str()` function or print the object. - Its primary goal is to be readable and present the object in a way that is understandable to end users. ### `__repr__` Method: - The `__repr__` method is intended for developers and debugging purposes. It should provide a more detailed and unambiguous representation of the object, ideally one that could be used to recreate the object if passed to `eval()`. - The output of `__repr__` should be clear and unambiguous, and if possible, it should include all necessary details about the object. ### Example: Here's an example that illustrates the difference between `__str__` and `__repr__` methods in a simple class: ```python class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name}, {self.age} years old" def __repr__(self): return f"Person(name='{self.name}', age={self.age})" # Create an instance of Person person = Person("Alice", 30) # Using __str__ print(str(person)) # Output: Alice, 30 years old print(person) # Output: Alice, 30 years old (because print calls str()) # Using __repr__ print(repr(person)) # Output: Person(name='Alice', age=30) ``` ### Key Takeaways: - Use `__str__` when you want a string that is easy to read, suitable for display to end users. - Use `__repr__` for a string that is more appropriate for debugging and development, ideally providing enough information to recreate the object. - If `__str__` is not defined, Python will use `__repr__` as a fallback when you call `print()` or `str()`.