What is the purpose of the __str__() method in Python?

Python >   Python Classes and Objects >   Python Introduction to OOP  

Long Question

300


Answer:

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.


This Particular section is dedicated to Question & Answer only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.