如何使用 NotImplemented

version python3.5.3

NotImplemented 是 Python 中的一個內建常量,文檔中表述如下

This object is returned from comparisons and binary operations when they are asked to operate on types they don’t support. See Comparisons for more information. There is exactly one NotImplemented object. type(NotImplemented)() produces the singleton instance.

當比較操作和二元運算中遇到不支持的類型時,會返回這個對象

根據(jù)個人淺薄的編程經(jīng)驗來說,遇到不支持的類型時,我常常會 raise NotImplementedError;而返回常量 NotImplemented 的這種處理方式有點像 C 的風格

那么這種形式有什么好處呢

當我們進行對象間的比較時(調用對象的 __eq__, __lt__),如果對應的方法返回了 NotImplemented,則會從右操作數(shù)的角度調用方法進行比較。
如下:

In [22]: class A(object):
    ...:     def __init__(self, num):
    ...:         self.num = num
    ...:     def __eq__(self, other):
    ...:         print('call A __eq__')
    ...:         return NotImplemented
    ...:         
    ...:     

In [23]: class B(object):
    ...:     def __init__(self, num):
    ...:         self.num = num
    ...:     def __eq__(self, other):
    ...:         print('call B __eq__')
    ...:         return self.num == other.num
    ...:     

In [24]: a = A(2)

In [25]: b = B(2)

In [26]: a == b
call A __eq__
call B __eq__
Out[26]: True

In [27]: b == a
call B __eq__
Out[31]: True

可以看到首先調用了 a.__eq__(b),由于返回了 NotImplemented 常量,所以 b.__eq__(a) 被調用。

對應的如下

comparison | |
-------------|------------------|--------------
a < b | a.__lt__(b) | b.__gt__(a)
a <= b | a.__le__(b) | b.__ge__(b)
a > b | a.__gt__(b) | b.__lt__(a)
a >= b | a.__ge__(b) | b.__le__(a)
a == b | a.__eq__(b) | b.__eq__(a)
a != b | a.__ne__(b) | b.__ne__(a)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容