以下是实现比较的 Python 源代码(is
、==
、<=
等):
Python/ceval.c:4501
static PyObject *
cmp_outcome(int op, register PyObject *v, register PyObject *w)
{
int res = 0;
switch (op) {
case PyCmp_IS:
res = (v == w);
break;
...
default:
return PyObject_RichCompare(v, w, op);
is
仅在一行代码中实现,一个简单的 C 指针比较。根据这个,一些 Python 原语比较相等(因为实习,或者因为它们是单例,如True
,False
和None
)。
另一方面,eq
使用PyObject_RichCompare
辅助函数实现的uses do_richcompare
:
richcmpfunc f;
PyObject *res;
int checked_reverse_op = 0;
if (v->ob_type != w->ob_type &&
PyType_IsSubtype(w->ob_type, v->ob_type) &&
(f = w->ob_type->tp_richcompare) != NULL) {
checked_reverse_op = 1;
res = (*f)(w, v, _Py_SwappedOp[op]);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
if ((f = v->ob_type->tp_richcompare) != NULL) {
res = (*f)(v, w, op);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
res = (*f)(w, v, _Py_SwappedOp[op]);
if (res != Py_NotImplemented)
return res;
Py_DECREF(res);
}
__eq__
这会检查参数类型,并可能在确定答案之前尝试多个比较函数(方法)。比较方法可能会做无限的工作(例如list.__eq__
,必须检查列表的每个元素,可能是递归的),但即使在简单的情况下x == None
,类型检查和所有额外的工作都会比is
.