【问题标题】:Why does NotImplemented evaluate to True?为什么 NotImplemented 评估为 True?
【发布时间】:2014-06-17 08:33:03
【问题描述】:

我最近偶然发现了 Python 的 NotImplemented 内置函数。经过一番阅读,我现在确实明白了它的目的,但我不明白为什么它评估为 True 作为布尔值。下面的例子让我觉得它像是某种残酷的玩笑:

>>> class A:
...     def __eq__(self, other):
...         return NotImplemented
... 
>>> 
>>> a = A()
>>> a == 1
False
>>> bool(a.__eq__(1))
True

我的问题很简单:为什么NotImplemented 会评估为True

【问题讨论】:

  • 通常应该引发异常,而不是返回
  • @RuggeroTurra NotImplemented 属于NotImplementedType 类型,它一点也不例外。 一个NotImplementedError;在这种情况下,我可能会将return NotImplemented 替换为raise NotImplementedError

标签: python


【解决方案1】:

因为它的计算结果不是False默认是考虑所有对象True,除非它们有length of 0(容器)或are zero(数字);见Truth Value Testing reference

然而,返回 NotImplemented 向 Python 发出信号,表示未实现相等测试,并尝试相反的 (1).__eq__(a)。如果该方法也不存在,则如果它们不是同一个对象,则对象不相等(a is 1False)。

换句话说,NotImplemented 是一个特殊的单例对象,是一个向 Python 发出信号的哨兵,表示您希望 Python 尝试其他方法,因为不支持此对象与另一个对象之间的相等性测试。

因此,它从未打算在布尔上下文中使用。它绝不是为了传达False

【讨论】:

  • 错字:应该是the default is to consider all objects True unless it has a length 0 (containers), or it evaluates to 0 (numeric) 一个非零值的数字对象应该是True
  • @Martijn Pieters:嗯,我仍然认为它的编写方式是倒退的,不是吗?应该是...the default is to consider all objects True unless they are 1) the False or None objects; or 2) have a length of 0 (containers), or 3) evaluate to zero (numeric); or 4) define __nonzero__. 如果某个数值的计算结果为非零,则为真。 bool(.00001)
猜你喜欢
  • 1970-01-01
  • 2015-03-15
  • 2013-11-11
  • 2017-01-26
  • 1970-01-01
  • 2014-02-16
  • 2020-08-15
  • 2012-03-06
  • 2013-09-02
相关资源
最近更新 更多