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