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 to the screen:

person = Person('John', 'Doe', 25) print(person)
Code language: PHP (php)

Output:

<__main__.Person object at 0x0000023CA16D13A0>
Code language: HTML, XML (xml)

When we use the print function to display the instance of the Person class, it 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 the instance, you’ll need to implement the __str__ magic method.

Python will call the __str__ method automatically when you call the str() on an instance of a class.

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

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:

person = Person('John', 'Doe', 25) print(person)
Code language: PHP (php)

Output:

Person(John,Doe,25)

Summary

  • Implement the __str__ method to customize the string representation of an instance of a class.
Did you find this tutorial helpful ?