Python using the magic method str to customize an object's printed output
In Python, the magic method __str__ defines an object's string representation. When you use the print() function to print an object, or use the str() function to convert an object to a string, Python automatically calls this method to obtain the object's string representation.
Below is a simple example showing how to use the __str__ method to customize an object's printed output.
Example
class
Person:
def
init
(
self
,
name
,
age
)
:
self
.
name
=
name
self
.
age
=
age
def
str
(
self
)
:
return
f
"Person(name={self.name}, age={self.age})"
Create a Person object
person
=
Person
(
"Alice"
,
30
)
Print the object
(
person
)
Code analysis:
__init__method is the class constructor, used to initialize the object's attributesnameandage。__str__The method defines the string representation of the object. In this example it returns a formatted string containing the object'snameandageattribute.- When we use
print(person)to print the object, Python automatically calls the__str__method and outputs the string it returns.
Output result:
Person(name=Alice, age=30)
Through customizing __str__ method, you can control the printed output of an object to make it more readable and informative.
Python3 Examples