Python __str__ Method Tutorial

In this section, we will learn what the __str__ method is and how to use it in Python.

What is __str__ Method in Python?

Let’s say you have a custom class and created an object from it.

Now that object is involved in an operation where a string type of value is needed! For example, the object is passed as the argument of the `print()` function! How should Python know which value to take from our object and pass that into the operation?

This is where the `__str__` method comes handy.

This method can be overridden in a class and it will return a string value as a result of calling it.

So if we override this method in a class, then python will call it to take its string value automatically when an object of that class type is involved in an operation where a string value is required.

Python __str__ Method Syntax

def __str__(self):

Python __str__ Method Parameters

The method takes one argument, and that is filled automatically by the Python execution engine itself.

Python __str__ Method Return Value

The return value of this method is a string value that will be used in an operation where a string is needed.

Example: using python __str__ method

class Parent: 
    
    def __str__(self):
        return "The name of this class is Parent"


par = Parent()

print(par)

Output:

The name of this class is Parent

Here we’ve passed the `par` object as the argument of the `print()` function and because this function needs a string value, then the execution engine called `__str__` method of the `par` object automatically and used the string value we’ve set as the return value of this method and sent it to the output stream.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies