Curriculum
In Python, the __str__ method is a special method that is used to define a string representation of an object. This method is called when the object is passed to the str() function or when the object is used in a string context (e.g. with the print() function). The __str__ method should return a string that represents the object in a human-readable format.
Here’s an example of how the __str__ method can be used in 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)"
p = Person("John", 25)
print(p) # Output: "John (25 years old)"
In this example, we define a Person class with two attributes: name and age. We also define a __str__ method that returns a string representation of the object that includes the person’s name and age.
When we create a new Person object and print it, the __str__ method is called and generates a string representation of the object that includes the person’s name and age. This allows us to easily print out information about a Person object in a human-readable format.
Note that the __str__ method is not the same as the __repr__ method, which is used to define a string representation of an object that can be used to recreate the object. The __str__ method is used for more general-purpose string formatting and should provide a human-readable output, while the __repr__ method should provide a more technical representation of the object.