python 對(duì)象屬性中的__repr__
& __str__
例子
class test_object(object):
pass
print str(test_object())
<__main__.test_object object at 0x037C9F90>
print repr(rest_object())
<__main__.test_object object at 0x037C9F90>
class test_object(object):
def __repr__(self):
return 'foo'
print str(test_object())
foo
print repr(test_object())
foo
class test_object(object):
def __str__(self):
return 'foo'
print str(test_object())
foo
print repr(test_object())
<__main__.test_object object at 0x037C9F90>
class test_object(object):
def __str__(self):
return 'foo'
def __repr__(self):
return 'foo2'
print str(test_object())
foo
print repr(test_object())
foo2
從上面可以看出如果程序修改了__repr__
绎橘,__str__
會(huì)自動(dòng)被重載啊片,而__str__
重寫后不會(huì)被__repr__
__str__
是保證對(duì)象的可讀性歉备,方便用戶查看信息谈竿。
__repr__
是保證對(duì)象的準(zhǔn)確性,讓程序員處理對(duì)象的時(shí)候更加精確沮尿。