Python uses the magic method __str__ to customize object print output
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)
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:
__init__The method is the constructor of the class, 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'snameandageattributes.- 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)
By customizing the__str__method, you can control the print output of an object, making it more readable and informative.
Python3 Examples