Python __str__ attribute

Share Your Love

In Python __str__ attribute is a special method that defines the string representation of an object. It is called by the built-in str() function and the print() function to obtain a printable string representation of the object.

The __str__ method should return a string that represents the object in a human-readable format. It is commonly used for debugging, logging, or displaying object information.

Here’s an example to illustrate the usage of the __str__ attribute:

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})"

person = Person("John", 30)
print(person)   # Output: Person(name='John', age=30)

In the example above, the Person class defines the __str__ the method that returns a formatted string representation of the Person object. The string contains the values of the name and age attributes.

When print(person) is called, it implicitly invokes the str(person) function, which in turn calls the __str__ method of the person object. The returned string is then printed to the console.

By providing a meaningful implementation of the __str__ method, you can customize how objects of your class are displayed as strings, making it easier to understand and debug your code.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter