In Python, you can redefine the string representation of an object by overriding the __str__ method in your class. The __str__ method is called by the str() function and, in many cases, by the print() function to compute the "informal" or nicely printable string representation of an object.
__str__pythonclass Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name}, age={self.age})" # Create an instance person = Person("Benjamin", 30) # Use str() function print(str(person)) # Output: Person(name=Benjamin, age=30) # Use print() function print(person) # Output: Person(name=Benjamin, age=30)
__str__ method should return a string.__str__, Python will use the __repr__ method as a fallback.__repr__ method is used for a more detailed, unambiguous representation of the object, often used for debugging.Would you like to see an example of overriding __repr__ as well?