2016-02-29 69 views
2

object是所有新款式的基础。我在哪里可以找到object的源代码?我想看看如何定义功能__hash__()__eq__()Python中对象__hash __()和__eq __()的源代码是什么?

请参阅此答案(Finding the source code for built-in Python functions?),我搜索cpython中的对象定义。

https://hg.python.org/cpython/file/tip/Objects/object.c中没有__hash__()__eq__() definiton。

+1

不知道对平等但散列你可能想看看[这个文件(https://github.com/python/cpython/blob/ master/Python/pyhash.c) –

+1

@Waylan:尽管它看起来像什么,但这些函数实际上并不是'object .__ eq__'或'object .__ hash__'实现。 – user2357112

回答

3

__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; 
} 
2

由于某些原因,object实现实际上是在Objects/typeobject.c中。看在该文件中,可以从PyBaseObject_Type definition看到:

PyTypeObject PyBaseObject_Type = { 
    PyVarObject_HEAD_INIT(&PyType_Type, 0) 
    "object",         /* tp_name */ 
    ... 
    (hashfunc)_Py_HashPointer,     /* tp_hash */ 
    ... 
    object_richcompare,       /* tp_richcompare */ 

object.__eq__object_richcompare实现,object.__hash___Py_HashPointerPython/pyhash.c实现。

Python 2.7

PyTypeObject PyBaseObject_Type = { 
    PyVarObject_HEAD_INIT(&PyType_Type, 0) 
    "object",         /* tp_name */ 
    ... 
    0,           /* tp_compare */ 
    ... 
    (hashfunc)_Py_HashPointer,     /* tp_hash */ 
    ... 
    0,           /* tp_richcompare */ 

object.__eq__根本不存在,所以==最终回落在default_3way_compare一个指针比较。 _Py_HashPointer仍然存在,但它在Objects/object.c