NotImplemented 是一個非異常對象,NotImplementedError 是一個異常對象。
>>> NotImplemented NotImplemented >>> NotImplementedError <type 'exceptions.NotImplementedError'> >>> type(NotImplemented) <type 'NotImplementedType'> >>> type(NotImplementedError) <type 'type'>
如果拋出 NotImplemented 會得到 TypeError,因為它不是一個異常。而拋出 NotImplementedError 會正常捕獲該異常。
>>> raise NotImplemented Traceback (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 NotImplementedError Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> raise NotImplementedError NotImplementedError
為什么要存在一個 NotImplemented 和一個 NotImplementedError 呢?
在 Python 中對列表進行排序時,會經常間接使用像 __lt__() 這類比較運算的方法。
有時 Python 的內部算法會選擇別的方法來確定比較結果,或者直接選擇一個默認的結果。如果拋出一個異常,則會打破排序運算,因此如果使用 NotImplemented 則不會拋出異常,這樣 Python 可以嘗試別的方法。
NotImplemented 對象向運行時環境發出一個信號,告訴運行環境如果當前操作失敗,它應該再檢查一下其他可行方法。例如在 a == b 表達式,如果 a.__eq__(b) 返回 NotImplemented,那么 Python 會嘗試 b.__eq__(a)。如果調用 b 的 __eq__() 方法可以返回 True 或者 False,那么該表達式就成功了。如果 b.__eq__(a) 也不能得出結果,那么 Python 會繼續嘗試其他方法,例如使用 != 來比較。
