有時候我們想讓屏幕打印的結果不是對象的內存地址,而是它的值或者其他可以自定義的東西,以便更直觀地顯示對象內容,可以通過在該對象的類中創建或修改__str__()
或__repr__()
方法來實現(顯示對應方法的返回值)
注意:__str__()
方法和__repr__()
方法的返回值只能是字符串!
關於調用兩種方法的時機
- 使用print()時
- 使用%s和f'{}'拼接對象時
- 使用str(x)轉換對象x時
在上述三種場景中,會優先調用對象的__str__()
方法;若沒有,就調用__repr__()
方法;若再沒有,則顯示其內存地址。
特別地,對於下面兩種場景:
- 用%r進行字符串拼接時
- 用repr(x)轉換對象x時
則會調用這個對象的__repr__()
方法;若沒有,則不再看其是否有__str__()
方法,而是顯示其內存地址。
Django中打印queryset時,會調用__repr__方法
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