class TestClass:
def __init__(self):
pass
def __str__(self):
return 'You have called __str__'
def __repr__(self):
return 'You have called __repr__'
a = TestClass()
print(object.__repr__(a))
print(object.__str__(a))
輸出:
<__main__.TestClass object at 0x7fe175c547c0>
You have called __repr__
這兩個函式有什么作用?
我的理解是呼叫str(a)回傳a.__str__()和呼叫repr(a)回傳a.__repr__()。print(a)還列印字串,a.__str__()因為str(a)正在進行隱式轉換。
請注意,我的問題與另一個熱門問題不重復;請參閱下面的第一條評論。
這種行為是違反直覺的;列印reprprint(object.__str__(a))字串而不是 str 字串。
uj5u.com熱心網友回復:
該類為和方法object提供默認實作。__repr____str__
object.__repr__顯示物件的型別及其id(CPython中物件的地址)object.__str__(a)來電repr(a)。基本原理是,如果__str__在類中沒有被覆寫,str(a)將自動呼叫repr(a),使用可能的覆寫__repr__。更準確地說,Python 語言參考/資料模型/特殊方法名稱/基本自定義的官方檔案說:object.__str__(self)...內置型別物件呼叫定義的默認實作
object.__repr__()。...這反過來又呼叫了被覆寫的
__repr__方法,就像repr(object)會做的那樣。
這正是這里發生的情況,因為您在object.__str__不期望的情況下直接呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464568.html
