哈希函数如下:
long
PyObject_Hash(PyObject *v)
{
PyTypeObject *tp = v->ob_type;
if (tp->tp_hash != NULL)
return (*tp->tp_hash)(v);
/* To keep to the general practice that inheriting
* solely from object in C code should work without
* an explicit call to PyType_Ready, we implicitly call
* PyType_Ready here and then check the tp_hash slot again
*/
if (tp->tp_dict == NULL) {
if (PyType_Ready(tp) < 0)
return -1;
if (tp->tp_hash != NULL)
return (*tp->tp_hash)(v);
}
if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
return _Py_HashPointer(v); /* Use address as hash value */
}
/* If there's a cmp but no hash defined, the object can't be hashed */
return PyObject_HashNotImplemented(v);
}
搜索过程则是根据hash值确定表项位置,进行比较。
如果表项比较成功或者表现是Unused状态,返回。
如果表现是Dummy状态,则设置freeslot指向该位置,并向下一个位置进行比较。
for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
i = (i << 2) + i + perturb + 1;
ep = &ep0[i & mask];

本文详细解析了Python中对象的哈希函数实现机制,包括如何根据类型定义的哈希方法来计算对象的哈希值,以及当哈希方法未定义时的默认行为。此外还介绍了哈希表的搜索流程。

被折叠的 条评论
为什么被折叠?



