python - Python中object的__hash__()和__eq__()的源代码是什么?

标签 python python-internals

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/

相关文章:

python - 在Python中打印列表元素和字符串有不同的结果

python - 如何在 Bokeh (Python) 中处理图像

python - 使用 pandas 从开始时间和持续时间(分钟)计算结束时间。标准方法错误

python - python中3D数据的线性插值

Python:ZODB 文件大小不断增长 - 未更新?

python - 设置继承自 int 或 float 或 str 的类中参数的值

python - list() 使用的内存比列表推导略多

python - 为什么这个 Python 字符串的大小在 int 转换失败时会发生变化

python - 为什么2⁶³的大小是36字节,而2⁶³-1只有24字节?