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
Code language: Python (python)
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)
Code language: Python (python)
Output:
<__main__.Person object at 0x0000023CA16D13A0>
Code language: Python (python)
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})'
Code language: Python (python)
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: Python (python)
Output:
Person(John,Doe,25)
Code language: Python (python)
Summary
- Implement the
__str__
method to customize the string representation of an instance of a class.