What is the __str__ method in Python?
Explore how to use the __str__ method in Python to create readable string representations of class objects. Understand the default behavior, how to define custom outputs, and the relationship with the __repr__ method. This lesson helps you write clearer, more user-friendly code and debug effectively by customizing object displays.
We'll cover the following...
The __str__ method represents a class's objects as a string. It should be defined so that the output is easy to read and includes the relevant members of the class, which also makes it useful as a debugging tool when you need to inspect an object's contents.
Python automatically calls __str__ when any of the following are used on an object:
print(obj)str(obj)obj.__str__()
If __str__ isn't defined on the class, Python falls back to __repr__ instead. By default, __repr__ returns a string describing the object's pointer (memory address), so without a custom __str__, printing your object will show something cryptic rather than a readable summary.
In the next sections, we'll look at two ways to use __str__: relying on the default behavior, and defining a custom version.
1. Default implementation
The following code explains the default implementation of the __str__ method.
The above code shows an example where neither __str__ nor __repr__ are defined. Calling __str__ calls the default __repr__ method, and they all give the same output, the pointer of our object.
2. Custom __str__method
The following code explains how the custom __str__ method works.
The code above shows the output once you have defined the __str__ method. When __str__, print(), or str() are called you will get your defined output. Make note that the __repr__ output remains the same.
3. The __repr__method defined only
Let’s see the example of the __repr__ method defined only.
In the first example we saw that when __str__ is not defined it automatically calls the __repr__ method. Therefore, the output of all the functions - __str__, str(), and __repr__ - are the same. Moreover, the __repr__ method does not necessarily need to return a string. In case it does not return a string, the print() statements will throw an error.