Python __str__() Method
The __str__() Method
The __str__() method is a magic method that controls what is returned when the object is printed, or passed to str().
Example
Without __str__(), printing an object shows its memory address:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 36)
print(p1)
Try it Yourself »
Add a __str__() method to control what is shown instead:
Example
Return a readable text representation of the object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
p1 = Person("Tobias", 25)
print(p1)
Try it Yourself »
__str__() Must Return a String
__str__() must return a string. If it returns anything else, Python raises a TypeError.
Example
This __str__() method returns a number instead of a string, which raises an error:
class Person:
def __init__(self, age):
self.age = age
def __str__(self):
return self.age
p1 = Person(36)
print(p1)
Try it Yourself »