__str__

__str__是被print函数调用的,一般都是return一个什么东西。这个东西应该是以字符串的形式表现的。如果不是要用str()函数转换。当你打印一个类的时候,那么print首先调用的就是类里面的定义的__str__

 1 class Person(object):
 2     def __init__(self, name, job = None, pay = 0):
 3         self.name = name
 4         self.job = job
 5         self.pay = pay
 6 
 7     def lastName(self):
 8         return self.name.split()[-1]
 9 
10     def giveRaise(self, percent):
11         self.pay = int(self.pay * (1 + percent))
12 
13     def __str__(self):
14         return "[Person: %s, %s]" % (self.name, self.pay)
15 
16 
17 class Manager(Person):
18     def giveRaise(self, percent, bonus = 0.10):
19         Person.giveRaise(self, percent + bonus)
20 
21 
22 if __name__ == '__main__':
23     bob = Person('Bob Smith')
24     sue = Person('Sue Jones', job = 'dev', pay = 100000)
25     tom = Manager('Tom Jones', 'mgr', 50000)
26 
27     for object in (bob, sue, tom):
28         object.giveRaise(0.10)
29         print object

 在看几个简单的例子:

 1 class strTest(object):
 2     def __init__(self):
 3         print "init: this is only test"
 4 
 5     def __str__(self):
 6         return "str: this is only test"
 7 
 8 if __name__ == '__main__':
 9     st = strTest()
10     print st

运行结果:
init: this is only test
str: this is only test

可以看出,当打印 strTest 的一个实例 st 的时候, __str__ 函数被调用到了。

python 中的对象基本都默认有 __str__ 函数,供 print 函数调用。

再看例子,如果在函数 __str__ 里返回的不是字符串:

 1 class strTest(object):
 2     def __init__(self):
 3         self.val = 1
 4 
 5     def __str__(self):
 6         return self.val
 7 
 8 if __name__ == '__main__':
 9     st = strTest()

10     print st

运行结果:
>>>
Traceback (most recent call last):
  File "<模块1>", line 11, in <module>
TypeError: __str__ returned non-string (type int)

错误信息提示:__str__ 返回了一个非字符串。

修改上述例子:

 1 class strTest(object):
 2     def __init__(self):
 3         self.val = 1
 4 
 5     def __str__(self):
 6         return str(self.val)
 7 
 8 if __name__ == '__main__':
 9     st = strTest()
10     print st

运行结果:
>>>
1

用 str()将整型转换城字符串

原文地址:https://www.cnblogs.com/Roger1227/p/3229040.html