The str method

__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

 

posted @ 2014-10-02 20:23  平静缓和用胸音说爱  阅读(218)  评论(0编辑  收藏  举报