注意:__str__()
方法和__repr__()
方法的返回值只能是字符串!
关于调用两种方法的时机
-
使用print()时
-
使用%s、
f'{}'
拼接对象时 -
使用str(x)转换对象x时
在上述三种场景中,会优先调用对象的__str__()
方法;若没有,就调用__repr__()
方法;若再没有,则显示其内存地址。
特别地,对于下面两种场景:
-
用%r进行字符串拼接时
-
用repr(x)转换对象x时
则会调用这个对象的__repr__()
方法;若没有,则不再看其是否有__str__()
方法,而是显示其内存地址。
扫描二维码关注公众号,回复:
6380256 查看本文章
为便于理解,使用下面的直观例子进行说明:
class A(object): pass class B(object): def __str__(self): return '1' class C(object): def __repr__(self): return '2' class D(object): def __str__(self): return '3' def __repr__(self): return '4' a=A() b=B() c=C() d=D() print(a,b,c,d) print('%s,%s,%s,%s'%(a,b,c,d)) print('%r,%r,%r,%r'%(a,b,c,d)) print(f'{a},{b},{c},{d}') print(str(a),str(b),str(c),str(d)) print(repr(a),repr(b),repr(c),repr(d))
执行结果:
<__main__.A object at 0x0000000002419630> 1 2 3 <__main__.A object at 0x0000000002419630>,1,2,3 <__main__.A object at 0x0000000002419630>,<__main__.B object at 0x0000000002419A58>,2,4 <__main__.A object at 0x0000000002419630>,1,2,3 <__main__.A object at 0x0000000002419630> 1 2 3 <__main__.A object at 0x0000000002419630> <__main__.B object at 0x0000000002419A58> 2 4