The __str__()
method returns the string representation of an object. If you have ever used the builtin str() function, you have also indirectly used the __str__()
method. This is because the builtin str() function actually calls __str__()
method on the target object. So when we are casting another type to string using the str()
function, we are just simply calling the __str__()
method on the respective object albeit indirectly.
The __str__()
method belongs to a category of methods known as the dunder(double underscore) or magic methods. It is meant to provide a human-friendly representation of an object and this makes it a useful tool for displaying, debugging and logging purposes..
Every object in Python, whether builtin or user-defined always have this method defined by default. This in turn makes it possible to call the str() function with literally any Python object.
Overriding the __str__() methods for user-defined objects
With user-defined objects, the __str__() method, by default returns a string providing general information such as the class the object belongs, and its memory address.
We can override this behavior by implementing the __str__() method on the class definition and making it return a more meaningful value.
A more practical example:
As you have seen above, defining the __str__
method in a class makes it possible to represent instances more specifically and in a more user-friendly format.
Like all other instance methods, the __str__
method must include the self
parameter in the definition. The method should not take any additional required parameter apart from self
, attempting this will result in a TypeError
being raised.
The __str__()
method should always return a string object, otherwise a TypeError
will be raised if you call the str()
function.
Conclusion:
- The
__str__()
method returns the string representation of an object - The builtin
str()
function literally calls the__str__()
method of the specified object. - All Python objects have the
__str__()
method defined by default - We can override the default
__str__(
) method in a class definition - The
__str__()
method should not include a required parameter apart fromself
. - The
__str__()
method must strictly return a string object, otherwise aTypeError
is raised.