即使这些比较没有意义,为什么
list() == 1
#return: False
but
list() > 1
#return: '>' not supported between instances of 'list' and 'int'
对我来说,两个比较运算符应该具有相同的行为,但事实并非如此。顺便说一句,我正在使用 Python 3.7。
这种行为可以在object.c的实现 https://github.com/python/cpython/blob/3.8/Objects/object.c#L731-L747:
/* Perform a rich comparison, raising TypeError when the requested comparison
operator is not supported. */
static PyObject *
do_richcompare(PyObject *v, PyObject *w, int op)
{
// (omitted some code for brevity)
/* If neither object implements it, provide a sensible default
for == and !=, but raise an exception for ordering. */
switch (op) {
case Py_EQ:
res = (v == w) ? Py_True : Py_False;
break;
case Py_NE:
res = (v != w) ? Py_True : Py_False;
break;
default:
PyErr_Format(PyExc_TypeError,
"'%s' not supported between instances of '%.100s' and '%.100s'",
opstrings[op],
v->ob_type->tp_name,
w->ob_type->tp_name);
return NULL;
}
Py_INCREF(res);
return res;
}
看着引入此更改的提交 https://github.com/python/cpython/commit/47b9ff6ba11fab4c90556357c437cb4feec1e853似乎有意决定只支持平等而不支持不同类型对象的比较。
引用提交消息中的摘要行:
大幅重组比较。不再有默认值ordering物体之间;只有默认的相等测试
(由仅等于其自身的对象定义)。
...此后消息继续描述基本原理(以及此更改的一些缺点)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)