_str_函数可以将类变成一个字符串。。。。。。。。。
上程序看吧,清晰明了
这是没有加 str 函数的结果
>>> class Fruit(object):
def __init__(self, size, color):
self.size = size
self.color = color
>>> p=Fruit(20,'red')
>>> print p
<__main__.Fruit object at 0x028D1AB0>
>>> p
<__main__.Fruit object at 0x028D1AB0>
>>>
加上 str 函数的
>>> class Fruit(object):
def __init__(self, size, color):
self.size = size
self.color = color
def __str__(self):
return'(Fruit: %d,%s)' % (self.size,self.color)
>>> p = Person('Bob', 'male')
>>> print p
(Person: Bob, male)
>>> p
(Person: Bob, male)
>>>