我不明白 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__
?
最佳答案
bool(x)
是True
如果x
是一个没有你提到的返回 False
的神奇方法之一的对象.这就是为什么 Ellipsis
评估为 True
.
None
是special-cased在bool()
并让它返回 False
.
详细信息:
bool()
使用 PyObject_IsTrue()
2.7.2 中的 API 函数如下所示:
int
PyObject_IsTrue(PyObject *v)
{
Py_ssize_t res;
if (v == Py_True)
return 1;
if (v == Py_False)
return 0;
if (v == Py_None)
return 0;
else if (v->ob_type->tp_as_number != NULL &&
v->ob_type->tp_as_number->nb_nonzero != NULL)
res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
else if (v->ob_type->tp_as_mapping != NULL &&
v->ob_type->tp_as_mapping->mp_length != NULL)
res = (*v->ob_type->tp_as_mapping->mp_length)(v);
else if (v->ob_type->tp_as_sequence != NULL &&
v->ob_type->tp_as_sequence->sq_length != NULL)
res = (*v->ob_type->tp_as_sequence->sq_length)(v);
else
return 1;
/* if it is negative, it should be either -1 or -2 */
return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
}
关于Python boolean (省略号)和 boolean (无),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8720711/