python - 为什么 NotImplemented 在 Python 3 中是真实的?

标签 python python-3.x boolean truthiness

这个问题是从 this question 的回答和讨论中提出来的.以下片段显示了问题的关键:

>>> bool(NotImplemented)
True

我的问题如下:

  1. 为什么决定 NotImplementedbool 值应该是 True?感觉不像 python 。
  2. 有什么我不知道的充分理由吗?文档似乎只是说,“因为它是”。
  3. 有没有以合理方式使用它的示例?

我认为它不直观的原因(请忽略缺乏最佳实践):

>>> class A:
...     def something(self):
...         return NotImplemented
...
>>> a = A()
>>> a.something()
NotImplemented
>>> if a.something():
...     print("this is unintuitive")
...
this is unintuitive

具有如此负面含义(缺乏实现)的东西会被认为是真实的,这似乎是一种奇怪的行为。

相关文字来自:

NotImplemented

Special value which should be returned by the binary special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type; may be returned by the in-place binary special methods (e.g. __imul__(), __iand__(), etc.) for the same purpose. Its truth value is true.

— From the Python Docs

编辑 1

为了澄清我的立场,我觉得 NotImplemented 能够评估为 boolean 值本身就是一种反模式。我觉得 Exception 更有意义,但普遍的想法是,在评估不同对象之间的比较时,出于性能原因选择常量单例。我想我正在寻找令人信服的理由来说明为什么选择这种“方式”。

最佳答案

默认情况下,一个对象被认为是真实的(bool(obj) == True),除非它的类提供了一种方法来覆盖它的真实性。在NotImplemented的情况下,没有人为 bool(NotImplemented) 提供过令人信服的用例返回 False ,等等 <class 'NotImplementedType'>从未提供覆盖。

关于python - 为什么 NotImplemented 在 Python 3 中是真实的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54134467/

相关文章:

javascript - 在 kendo.ui.GridColumn 中格式化日期和 boolean 值

ios - 如何在 Objective C 中创建一个强大的 boolean 值

python - 在一系列 Python 版本中支持 unittest2 功能的最 Pythonic 方式是什么?

python - pip install numpy pandas 失败?

python - 用于分析 Python 代码的峰值内存使用情况的模块

python - 函数的输入参数是否总是默认返回?

c - Objective C boolean 数组

python - 重叠的正则表达式

python - 使用 Python 查找隐式函数的根

python - 如何在 Pandas 中打开文件