这个问题是从 this question 的回答和讨论中提出来的.以下片段显示了问题的关键:
>>> bool(NotImplemented)
True
我的问题如下:
- 为什么决定
NotImplemented
的bool
值应该是True
?感觉不像 python 。 - 有什么我不知道的充分理由吗?文档似乎只是说,“因为它是”。
- 有没有以合理方式使用它的示例?
我认为它不直观的原因(请忽略缺乏最佳实践):
>>> 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/