日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

[Python] NotImplemented 和 NotImplementedError 区别

發(fā)布時間:2023/12/20 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Python] NotImplemented 和 NotImplementedError 区别 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

  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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。