The __str__() method in Python is a special method that is called by the str() built-in function and by Python's print statement to compute the "informal" or nicely printable string representation of an object. It returns a string that represents the object.
The __str__() method takes the self parameter, which refers to the object whose string representation is being computed. It must return a string object.
For example, consider the following code:
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name}, {self.age} years old" person = Person("Alice", 30) print(person)
In this example, the Person class defines a __str__() method that returns a string representation of the object. The __str__() method uses an f-string to format the name and age attributes of the object as a string.
When the print() function is called with the person object, it automatically calls the __str__() method to compute the string representation of the object. This prints the string "Alice, 30 years old".
By using the __str__() method, the Person class can define a custom string representation for objects of the class. This makes the code more readable and makes it easier to debug and understand the behavior of the code.
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.