[Python] NotImplemented 和 NotImplementedError 区别
NotImplemented 是一個(gè)非異常對(duì)象,NotImplementedError 是一個(gè)異常對(duì)象。
>>> NotImplemented NotImplemented >>> NotImplementedError <type 'exceptions.NotImplementedError'>>>> type(NotImplemented) <type 'NotImplementedType'> >>> type(NotImplementedError) <type 'type'>?
如果拋出 NotImplemented 會(huì)得到 TypeError,因?yàn)樗皇且粋€(gè)異常。而拋出 NotImplementedError 會(huì)正常捕獲該異常。
>>> raise NotImplementedTraceback (most recent call last):File "<pyshell#10>", line 1, in <module>raise NotImplemented TypeError: exceptions must be old-style classes or derived from BaseException, not NotImplementedType>>> raise NotImplementedErrorTraceback (most recent call last):File "<pyshell#11>", line 1, in <module>raise NotImplementedError NotImplementedError?
為什么要存在一個(gè) NotImplemented 和一個(gè) NotImplementedError 呢?
在 Python 中對(duì)列表進(jìn)行排序時(shí),會(huì)經(jīng)常間接使用像 __lt__() 這類(lèi)比較運(yùn)算的方法。
有時(shí) Python 的內(nèi)部算法會(huì)選擇別的方法來(lái)確定比較結(jié)果,或者直接選擇一個(gè)默認(rèn)的結(jié)果。如果拋出一個(gè)異常,則會(huì)打破排序運(yùn)算,因此如果使用 NotImplemented 則不會(huì)拋出異常,這樣 Python 可以嘗試別的方法。
NotImplemented 對(duì)象向運(yùn)行時(shí)環(huán)境發(fā)出一個(gè)信號(hào),告訴運(yùn)行環(huán)境如果當(dāng)前操作失敗,它應(yīng)該再檢查一下其他可行方法。例如在 a == b 表達(dá)式,如果 a.__eq__(b) 返回 NotImplemented,那么 Python 會(huì)嘗試 b.__eq__(a)。如果調(diào)用 b 的 __eq__() 方法可以返回 True 或者 False,那么該表達(dá)式就成功了。如果 b.__eq__(a) 也不能得出結(jié)果,那么 Python 會(huì)繼續(xù)嘗試其他方法,例如使用 != 來(lái)比較。
?
參考一
轉(zhuǎn)載于:https://www.cnblogs.com/ifantastic/p/3682268.html
總結(jié)
以上是生活随笔為你收集整理的[Python] NotImplemented 和 NotImplementedError 区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 你知道手动探针台系统的用途及组成部分吗?
- 下一篇: 关于转正