object
是所有新样式类的基础。在哪里可以找到object
的源代码?我想看看函数 __hash__()
和 __eq__()
是如何定义的。
引用这个答案(Finding the source code for built-in Python functions?),我在cpython中搜索对象定义.
https://hg.python.org/cpython/file/tip/Objects/object.c 中没有__hash__()
和__eq__()
定义| .
最佳答案
__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;
}
关于python - Python中object的__hash__()和__eq__()的源代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35709339/