Junior — Middle
Why is it recommended to implement the __str__ method in Python and what is its purpose?
sobes.tech AI
Answer from AI
The __str__ method in Python is responsible for the string representation of an object that is easy for humans to read. Its implementation allows calling print(obj) or str(obj) to produce a clear and informative description of the object.
If __str__ is not implemented, Python uses the __repr__ method, which is often less readable.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
p = Person("Ivan", 30)
print(p) # Outputs: Person(name=Ivan, age=30)
Thus, __str__ enhances the ease of debugging and interacting with objects.