为__hash__
和__eq__
的缺省实现从基object
类型继承。您可以在typeobject.c
找到它的类型定义:
PyTypeObject PyBaseObject_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"object", /* tp_name */
…
(hashfunc)_Py_HashPointer, /* tp_hash */
…
object_richcompare, /* tp_richcompare */
…
};
散列函数(tp_hash
),用于参考的默认哈希函数,_Py_HashPointer
。它在pyhash.c
中定义:
Py_hash_t
_Py_HashPointer(void *p)
{
Py_hash_t x;
size_t y = (size_t)p;
/* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
excessive hash collisions for dicts and sets */
y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
x = (Py_hash_t)y;
if (x == -1)
x = -2;
return x;
}
这基本上使用指针地址作为哈希的基础。
当调用__eq__
时,Python在底层执行的操作是执行丰富的比较(tp_richcompare
)。这包括平等和不平等检查以及比较大于或小于的比较。默认实现使用object_richcompare
这需要一个参考平等:
static PyObject *
object_richcompare(PyObject *self, PyObject *other, int op)
{
PyObject *res;
switch (op) {
case Py_EQ:
/* Return NotImplemented instead of False, so if two
objects are compared, both get a chance at the
comparison. See issue #1393. */
res = (self == other) ? Py_True : Py_NotImplemented;
Py_INCREF(res);
break;
…
}
return res;
}
不知道对平等但散列你可能想看看[这个文件(https://github.com/python/cpython/blob/ master/Python/pyhash.c) –
@Waylan:尽管它看起来像什么,但这些函数实际上并不是'object .__ eq__'或'object .__ hash__'实现。 – user2357112