最近我偶然发现了Python的NotImplemented
内置函数。经过一些阅读,我现在明白了它的用途,但我不明白为什么它作为布尔值时会评估为True
。下面的示例让我觉得这像是某种残酷的玩笑:
>>> class A:
... def __eq__(self, other):
... return NotImplemented
...
>>>
>>> a = A()
>>> a == 1
False
>>> bool(a.__eq__(1))
True
我的问题很简单:为什么
NotImplemented
的评估结果是True
?
NotImplemented
是NotImplementedType
类型,它根本不是异常。确实存在一个NotImplementedError
;在这种情况下,我可能会用raise NotImplementedError
替换return NotImplemented
。 - Matthew Trevor