Python uses the magic method __str__ to customize object print output

Document 对象参考手册Python3 Examples

In Python, the magic method__str__is used to define the string representation of an object. When you use theprint()function to print an object, or use thestr()function to convert an object to a string, Python automatically calls this method to obtain the string representation of the object.

Here is a simple example showing how to use the__str__method to customize the print output of an object.

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__The method is the constructor of the class, used to initialize the object's attributesnameandage。
  2. __str__The method defines the string representation of the object. In this example, it returns a formatted string containing the object'snameandageattributes.
  3. When we useprint(person)to print the object, Python automatically calls the__str__method and outputs the string it returns.

Output result:

Person(name=Alice, age=30)

By customizing the__str__method, you can control the print output of an object, making it more readable and informative.

Document 对象参考手册Python3 Examples

Other extensions