How To Use __Str__ In Python

Using the str method in Python is a helpful way to make your classes more readable and user-friendly.

This tutorial will teach you how to use the str method to define how your custom Python objects should be represented as strings.

By the end of this tutorial, you’ll be able to use the str method to customize the string representation of your Python classes.

Step 1: Understanding the __str__ method

In Python, the str method is a special method within a class that defines how an object of that class should be represented as a string. The str method is automatically called by built-in functions like print() and str() to provide a more human-readable representation of the object.

The default implementation of the str method in Python simply returns the object’s memory address. However, by defining your own str method, you can provide an informative and more readable representation of the object that is suitable for display purposes or debugging.

For example, suppose we have a simple Person class with name and age as its attributes:

If we create an instance of the Person class and try to print it, we’ll get a less meaningful output:

Output:

<__main__.Person object at 0x7f672175efd0>

To improve the output, we can define a str method in the Person class.

Step 2: Defining the __str__ method

To define the str method in your class, simply add a method with the name str that returns a string.

Here’s the updated Person class with the str method:

Now, when we create an instance of the Person class and try to print it, we’ll get a more readable output:

Output:

Person(name=Alice, age=30)

Step 3: Using the __str__ method with built-in functions

The str method is not only utilized by the print() function, but it is also used by other built-in functions, such as str() and format(). Here’s an example:

Output:

Person(name=Alice, age=30)
The person's details are: Person(name=Alice, age=30)

As you can see, the str method is called whenever a string representation is required for the object.

Full code example

Conclusion

In summary, the str method is an important part of making your Python classes more readable and user-friendly. By defining your own str method, you can provide a custom and meaningful string representation for your objects that make them easier to understand and work within different contexts.