国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解Python中內置的NotImplemented類型的用法

2020-02-23 00:29:00
字體:
來源:轉載
供稿:網友

它是什么?
 

>>> type(NotImplemented)<type 'NotImplementedType'>

NotImplemented 是Python在內置命名空間中的六個常數之一。其他有False、True、None、Ellipsis 和 __debug__。和 Ellipsis很像,NotImplemented 能被重新賦值(覆蓋)。對它賦值,甚至改變屬性名稱, 不會產生 SyntaxError。所以它不是一個真正的“真”常數。當然,我們應該永遠不改變它。 但是為了完整性:
 

>>> None = 'hello'...SyntaxError: can't assign to keyword>>> NotImplementedNotImplemented>>> NotImplemented = 'do not'>>> NotImplemented'do not'

它有什么用?什么時候用?

NotImplemented 是個特殊值,它能被二元特殊方法返回(比如__eq__() 、 __lt__()  、 __add__() 、 __rsub__() 等),表明某個類型沒有像其他類型那樣實現這些操作。同樣,它或許會被原地處理(in place)的二元特殊方法返回(比如__imul__()、__iand__()等)。還有,它的實際值為True:
 

>>> bool(NotImplemented)True

你也許會問自己,“但我認為當這個操作沒有實現時,我應該產生個NotImpementedError”。我們會看些例子,關于為什么當實現二元特殊方法時不是這么回事兒。

讓我們看看NotImplemented常數的用法,通過__eq__()對于兩個非常基本(且沒用)的類 A 和 B 的編碼。[對于這個簡單的例子,為了避免干擾,不會實現__ne__() ,但是總的說來,每次實現__eq__() 時, __ne__()也應該被實現,除非,有個足夠充分的理由去不實現它。]
 

# example.py class A(object):  def __init__(self, value):    self.value = value   def __eq__(self, other):    if isinstance(other, A):      print('Comparing an A with an A')      return other.value == self.value    if isinstance(other, B):      print('Comparing an A with a B')      return other.value == self.value    print('Could not compare A with the other class')    return NotImplemented class B(object):  def __init__(self, value):    self.value = value   def __eq__(self, other):    if isinstance(other, B):      print('Comparing a B with another B')      return other.value == self.value    print('Could not compare B with the other class')    return NotImplemented

現在,在解釋器中:
 

>>> from example import A, B>>> a1 = A(1)>>> b1 = B(1)

我們現在可以實驗下對于 __eq__() 不同的調用,看看發生了什么。作為提醒,在Python中,a == b會調用a.__eq__(b):
 

>>> a1 == a1Comparing an A with an ATrue

正如所望,a1等于a1(自己),使用類A中的__eq__()來進行這個比較的。比較b1和它自己也會產生類似結果:

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 固安县| 高清| 镇康县| 陇南市| 汝阳县| 常熟市| 渑池县| 睢宁县| 同德县| 湘阴县| 泗阳县| 兴业县| 沂源县| 麦盖提县| 肥城市| 东平县| 鄂伦春自治旗| 玉屏| 巧家县| 平南县| 莲花县| 福贡县| 潮安县| 绍兴市| 莫力| 罗山县| 琼中| 文成县| 南岸区| 和林格尔县| 泗洪县| 阿拉善右旗| 榆林市| 昔阳县| 乳山市| 苗栗市| 砚山县| 特克斯县| 西宁市| 靖安县| 普定县|