魔法方法——簡單定製(__str__ 和__repr__)
阿新 • • 發佈:2019-01-10
讀書筆記:
repr和str這兩個方法都是用於顯示的,str是面向使用者的,而repr面向程式設計師。
repr是representation及描述的意思。
想使用print(Object)顯示物件,那就需要重構str。想直接輸入類物件來列印,那就需要重構repr。
在python語言裡,str一般是格式是這樣的。
class A:
def __str__(self):
return "this is in str"
事實上,str是被print函式呼叫的,一般都是return一個什麼東西。這個東西應該是以字串的形式表現的。如果不是要用str()函式轉換。當你列印一個類的時候,那麼print首先呼叫的就是類裡面的定義的str
class strtest:
def __init__(self):
print ("init: this is only test" )
def __str__(self):
return "str: this is only test"
if __name__ == "__main__":
st=strtest()
print (st)
init: this is only test
str: this is only test
再舉一個粟子吧!
>>> class Test():
def __init__(self):
self.prompt = "hello,zss041962"
>>> t = Test()
>>> t
<__main__.Test object at 0x0000000002F3EF28>
>>> print(t)
<__main__.Test object at 0x0000000002F3EF28>
# 看到了麼?上面列印類物件並不是很友好,顯示的是物件的記憶體地址
# 下面我們重構下該類的__repr__以及__str__,看看它們倆有啥區別
>>> #重構__repr__
>>> class TestRepr(Test):
def __repr__(self):
return "Show:%s"%self.prompt
# 重構__repr__方法後,不管直接輸出物件還是通過print列印的資訊都按我們__repr__方法中定義的格式進行顯示了
>>> t1 = TestRepr()
>>> t1
Show:hello,zss041962
>>> print(t1)
Show:hello,zss041962
>>> #重構__str__
>>> class TestStr(Test):
def __str__(self):
return "Show: %s"%self.prompt
# 你會發現,直接輸出物件ts時並沒有按我們__str__方法中定義的格式進行輸出,而用print輸出的資訊卻改變了
>>> t2 = TestStr()
>>> t2
<__main__.TestStr object at 0x00000000031C33C8>
>>> print(t2)
Show: hello,zss041962