Python bool(省略号) 和 bool(无)
我不明白 Ellipsis
和 None
如何由 bool()
进行不同的处理,因为两者在相关属性方面似乎相同用于真理检验。
>>> bool(Ellipsis)
True
>>> bool(None)
False
>>> any([hasattr(Ellipsis, attr) for attr in ['__len__', '__bool__', '__nonzero__']])
False
>>> any([hasattr(None, attr) for attr in ['__len__', '__bool__', '__nonzero__']])
False
我还缺少其他用于真理测试的东西吗?
是否有任何其他对象(除了
None
之外)计算结果为False
且既不实现__len__
也不实现__nonzero__
>?
I don't understand how are Ellipsis
and None
handled differently by bool()
, when both seem to be identical in terms of the relevant attributes for truth-testing.
>>> bool(Ellipsis)
True
>>> bool(None)
False
>>> any([hasattr(Ellipsis, attr) for attr in ['__len__', '__bool__', '__nonzero__']])
False
>>> any([hasattr(None, attr) for attr in ['__len__', '__bool__', '__nonzero__']])
False
Is there something else I'm missing which is used for truth-testing?
Are there any other objects (besides
None
) which evaluate toFalse
that implement neither of__len__
or__nonzero__
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
x
是一个对象,并且没有您提到的返回False
的魔术方法之一,则bool(x)
为True
。这就是Ellipsis
计算结果为True
的原因。None
是特殊情况bool()
并使其返回False
。详细信息:
bool()
使用PyObject_IsTrue()
API 函数,在 2.7.2 中如下所示:bool(x)
isTrue
ifx
is an object without one of the magic methods you mentioned returningFalse
. That's whyEllipsis
evaluates toTrue
.None
is special-cased inbool()
and makes it returnFalse
.Details:
bool()
usesPyObject_IsTrue()
API function which in 2.7.2 looks like this:来自 Python 数据模型:
None
计算结果为 false,因为它是内置类型 指定这样做。正如您所说,您没有在Ellipsis
上定义__len__()
或__nonzero__()
。如果你想让它评估为 false,From the Python data model:
None
evaluates to false because it's a built-in type that is specified to do so. You did not define__len__()
or__nonzero__()
onEllipsis
, as you stated. If you want it to evaluate to false,