==
如果项目相同(is
),cpython的基础实现将跳过列表中项目的相等性检查()。
cpython使用此作为优化,假设身份暗示平等。
这记录在PyObject_RichCompareBool中,用于比较项目:
注意:如果o1和o2是同一对象,则PyObject_RichCompareBool()对于Py_EQ将始终返回1,对于Py_NE将始终返回0。
从listobject.c实现中:
/* Search for the first index where items are different */
for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
int k = PyObject_RichCompareBool(vl->ob_item[i],
wl->ob_item[i], Py_EQ);
// k is 1 if objects are the same
// because of RichCmopareBool's behavIoUr
if (k < 0)
return NULL;
if (!k)
break;
}
正如你可以看到,只要RichCompareBool
是1
(True
)的项目不检查。
从object.c的实现PyObject_RichCompareBool
:
/* Quick result when objects are the same.
Guarantees that identity implies equality. */
if (v == w) {
if (op == Py_EQ)
return 1;
else if (op == Py_NE)
return 0;
}
// ... actually deep-compare objects
要覆盖此内容,您必须手动比较各项。