wim*_*wim 4 python boolean python-2.7
当两者在真值测试的相关属性方面看起来完全相同时,我不明白如何处理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
Run Code Online (Sandbox Code Playgroud)
我还缺少其他用于真相测试的东西吗?
是否有任何其他对象(除此之外None)评估为False不实现__len__或__nonzero__?
bool(x)是True,如果x是没有的,你提到的返回魔术方法之一的对象False.这就是Ellipsis评估的原因True.
None是特殊的,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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
335 次 |
| 最近记录: |