Python 的 __str__ 和 __repr__ 方法對比
閱讀到 Strings 中關(guān)于轉(zhuǎn)換對象為字符串的內(nèi)容,介紹了 repr 函數(shù),趁著還沒有真正了解 Python 面向?qū)ο蟮纳枧c熱度,感性上理解一下 repr 與 str 這兩個(gè)函數(shù)的區(qū)別。
Python 的全局方法 repr 和 str 會映射到對象的 __repr__ 和 __str__ 的方法調(diào)用,還有 str(obj) 時(shí)會調(diào)用哪個(gè)方法,以及 print(obj) 和調(diào)試 Python 代碼時(shí)的對象顯示會調(diào)用哪個(gè)方法呢?這就是本文想要印證的內(nèi)容。
恰如 Java 的 System.out.println(obj) 或 'hello' + obj 都會調(diào)用 Java 對象的 toString() 方法,那么 Python 中是怎么一回事呢?
來自某本 Python 入門書的解釋 repr 和 str:
repr: formal string representation of a Python object str: informal string representation of a Python object,或者說 printable string representation首先 repr 是 representation 的意思,一個(gè)是正式,另一個(gè)是非正式,看起來 repr 比 str 顯得重要些。
對于內(nèi)置的 Python 對象我們可以用 repr, print, 和 str 函數(shù),如針對 list 類型
>>> repr([1,2])’[1, 2]’>>> print([1,2])[1, 2]>>> str([1,2])’[1, 2]’
但是具體上面三個(gè)函數(shù)中分別調(diào)用了 list 的什么方法就不可而知了,這時(shí)候定義一個(gè)自己的類最能說明問題。測試環(huán)境為 IntelliJ, 以調(diào)試截圖來說明分別為 __str__ 和 __repr__ 幾種組合情況
只定義了 __str__ 方法
說明:在只定義了 __str__ 方法的情況下
調(diào)試時(shí) IntelliJ 在行內(nèi)顯示對象為 __str__ 的輸出,但變量窗口中顯示的是默認(rèn)的 __repr__ 的輸出 repr 始終堅(jiān)持調(diào)用默認(rèn)的 __repr__ 方法 str 轉(zhuǎn)型函數(shù)調(diào)用了 __str__ 方法 print 調(diào)用了 __str__ 方法只定義了 __repr__ 方法
說明:在只定義了 __repr__ 方法的情況下,可以看出 __repr__ 方法極其強(qiáng)勢,它壟斷了一切的調(diào)用,repr, str, 和 print 函數(shù),甚至是 IntelliJ 的調(diào)試顯示都必須以 __repr__ 方法為核心。
以上所有的情況都是調(diào)用 __repr__ 方法,沒得選擇同時(shí)定義了 __repr__ 和 __str__ 方法
說明:在同時(shí)定義了 __repr__ 和 __str__ 方法的情況下,__str__ 方法反而能扳回來。除了明確的 repr 會調(diào)用 __repr__ 方法,和調(diào)試時(shí)變量窗口中顯示對象會調(diào)用 __repr__ 方法外,其他時(shí)候都是 __str__ 占優(yōu)。具體為
repr 和 IntelliJ 調(diào)試時(shí)變量窗口顯示變量調(diào)用 __repr__ 方法 IntelliJ 調(diào)試時(shí)行內(nèi)顯示變量調(diào)用了 __str__ 方法 str 轉(zhuǎn)型操作調(diào)用了對象的 __str__ 方法,這不能解釋為 informal 非正式的 print 調(diào)用了 __str__ 來獲得對象輸出字符串另外,格式化字符串時(shí)的調(diào)用的對象方法與 print 時(shí)是一樣的,例如下面的格式化代碼
f1 = '%s' % tf2 = '{}'.format(t)
Python 不知道像 Java 那樣由字符串加上一個(gè)對象
'this is ' + t #Java 中會展開為 'this is ' + t.toString()
Python 會報(bào)以下錯(cuò)誤
TypeError: can only concatenate str (not 'Test') to str
說這里的 + 號只能連接兩個(gè)字符串,除非定義了 __add__ 和 __radd__ 方法,對應(yīng)關(guān)系分別為
t = Test()z1 = ’hello’ + t #相當(dāng)于 t.__radd__(’hello’)z2 = t + ’hello’ #相當(dāng)于 t.__add__(’hello’)
Python 的 __xyz__ 也挺魔幻的。
以上就是Python 的 __str__ 和 __repr__ 方法對比的詳細(xì)內(nèi)容,更多關(guān)于Python __str__ 和 __repr__ 的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法2. idea配置jdk的操作方法3. SpringBoot+TestNG單元測試的實(shí)現(xiàn)4. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法5. python 浮點(diǎn)數(shù)四舍五入需要注意的地方6. Springboot 全局日期格式化處理的實(shí)現(xiàn)7. VMware中如何安裝Ubuntu8. Docker容器如何更新打包并上傳到阿里云9. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題10. JAMon(Java Application Monitor)備忘記
