def __str__
时间: 2023-10-22 13:08:03 浏览: 88
__str__ is a special method in Python that is used to return a string representation of an object. It is invoked when an object is passed to the built-in str() function or when the object is used in a string context (such as when it is printed).
For example, suppose we have a class called Person with instance variables name and age:
```
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
```
The __str__ method is defined to return a string that describes the object. In this case, it returns a string that concatenates the person's name and age.
When we create a Person object and print it:
```
p = Person("Alice", 30)
print(p)
```
The __str__ method is invoked automatically, and the output will be:
```
Alice is 30 years old
```
阅读全文