哈希函数如下:
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中哈希函数的实现原理,包括如何通过对象类型确定哈希值及特殊情况处理,如对象不可哈希时的处理方式。此外,还讨论了哈希表的搜索过程,包括如何根据哈希值确定表项位置并进行比较。

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



