Python boolean (省略号)和 boolean (无)

标签 python python-2.7 boolean

我不明白 EllipsisNone 如何被 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
  1. 我还遗漏了一些用于真实性检验的东西吗?

  2. 是否有任何其他对象(None 除外)的计算结果为 False,但既没有实现 __len__ 也没有实现 __nonzero__ ?

最佳答案

bool(x)True如果x是一个没有你提到的返回 False 的神奇方法之一的对象.这就是为什么 Ellipsis评估为 True .

Nonespecial-casedbool()并让它返回 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/

相关文章:

python - 用于循环初始化的矩阵(锯齿状数组)

python - 删除所有内容,但保留数字和点

c# - 正则表达式 c# 不应匹配 boolean 运算符

ruby-on-rails - Rails 3 find 命令不适用于 postgresql 数据库

postgresql - 具有 NULL 值的 bool_and 和 bool_or 的行为

python - 从元组中调用字典元素

python - 如何提取beautifulsoup中最后一段标签文本?

Python 幂乘法

python - 梯度下降实现——绝对误差问题

linux - centos中不同的python版本