简体   繁体   English

为什么NotImplemented评估为True?

[英]Why does NotImplemented evaluate to True?

I recently stumbled upon Python's NotImplemented builtin. 我最近偶然发现了Python的NotImplemented内置版。 After some reading I do get it's purpose now, but I don't see why it evaluates to True as a boolean. 经过一些阅读后,我确实得到了它的目的,但我不明白为什么它作为布尔值计算为True The following example makes it seem like some kind of cruel joke to me: 下面的例子让我觉得这是一种残酷的玩笑:

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

My question is simple: Why does NotImplemented evaluate to True ? 我的问题很简单:为什么NotImplemented评估为True

Because it doesn't evaluate to False ; 因为它没有评估为False ; the default is to consider all objects True unless they have a length of 0 (containers), or are zero (numeric); 默认是将所有对象视为True除非它们的长度为0 (容器),或者为零 (数字); see the Truth Value Testing reference . 请参阅真值测试参考

However , returning NotImplemented signals to Python that the equality test is not implemented, and the inverse (1).__eq__(a) is tried instead. 但是 ,向Python返回NotImplemented信号表示没有实现相等测试,而是尝试使用inverse (1).__eq__(a) If that method doesn't exist either, the objects are not equal if they are not the same object ( a is 1 is False ). 如果该方法也不存在,则如果它们不是同一个对象( a is 1则为False ),则它们不相等。

In other words, NotImplemented is a special singleton object, a sentinel to signal to Python that you want Python to try something else, as the equality test between this object and the other is not supported. 换句话说, NotImplemented是一个特殊的单例对象,一个向Python发送信号的标记,你希望Python尝试别的东西,因为不支持这个对象和另一个对象之间的相等性测试。

As such it was never meant to be used in a boolean context. 因此,它从未打算在布尔上下文中使用。 It is never meant to convey False . 它永远不会传达False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM