__str__ is a special method name, like __init__, that is supposed to return a string representation of an object.
For example, here is a str method for Time objects. When you print an object, Python invokes the str method. when I write a new class, I almost always start by writing __init__, which makes it easier to instantiate objects, and __str__, which is almost always useful for debugging.
def __str__(self): return (‘%.2d:%.2d:%.2d‘ % (self.hour,self.minute,self.second))
from Thinking in Python
时间: 2024-11-06 04:33:31