Python __str__

Summary: in this tutorial, you’ll learn how to use the Python __str__ method to make a string representation of a class.

Introduction to the Python __str__ method #

Let’s start with the Person class:

class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

The Person class has three instance attributes including first_name, last_name, and age.

The following creates a new instance of the Person class and display it:

person = Person('John', 'Doe', 25)
print(person)

Output:

<__main__.Person object at 0x0000023CA16D13A0>

When you use the print() function to display the instance of the Person class, the print() function shows the memory address of that instance.

Sometimes, it’s useful to have a string representation of an instance of a class. To customize the string representation of a class instance, the class needs to implement the __str__ magic method.

Internally, Python will call the __str__ method automatically when an instance calls the str() method.

Note that the print() function converts all non-keyword arguments to strings by passing them to the str() before displaying the string values.

The following illustrates how to implement the __str__ method in the Person class:

class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def __str__(self):
        return f'Person({self.first_name},{self.last_name},{self.age})'

And when you use the print() function to print out an instance of the Person class, Python calls the __str__ method defined in the Person class. For example:

class Person:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def __str__(self):
        return f'Person({self.first_name},{self.last_name},{self.age})'

person = Person('John', 'Doe', 25)
print(person)

Try it

Output:

Person(John,Doe,25)

Summary #

  • Implement the __str__ method to customize the string representation of an instance of a class.

Quiz #

Quiz

__str__ Method

6 questions

To assess understanding of the Python __str__ method and its usage in customizing the string representation of a class.

Was this helpful?