Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Customizing an Object's Printed Output with the __str__ Magic Method

Python using the magic method str to customize an object's printed output

Document Object Reference Manual Python3 Examples

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

print

(

person

)

Code analysis:

  1. __init__ method is the class constructor, used to initialize the object's attributes name and age。
  2. __str__ The method defines the string representation of the object. In this example it returns a formatted string containing the object's name and age attribute.
  3. 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.

Document Object Reference Manual Python3 Examples