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.
Example: Redefining __str__
python
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})"
# 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)
Key Points
The __str__ method should return a string.
If you don't define __str__, Python will use the __repr__ method as a fallback.
The __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?
Mar 29, 9:59pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.