当hash()在Python 3中调用method时,我注意到在使用int数据类型但使用stringtype 时,它不会返回长整数。
这应该这样工作吗?如果确实是这种情况,那么int对于具有短哈希值的类型,由于它太短会不会引起冲突?
for i in [i for i in range(5)]:
print(hash(i))
print(hash("abc"))
Run Code Online (Sandbox Code Playgroud)
结果:
0
1
2
3
4
4714025963994714141
Run Code Online (Sandbox Code Playgroud)
在CPython(默认的Python解释器实现)中,内置hash是通过以下方式完成的:
对于数字类型,数字x的哈希值基于对x的减数以质数P = 2 ** _ PyHASH_BITS-1为模。经过设计,每当x和y数值相等时,hash(x)== hash(y)即可。 ,即使x和y的类型不同
_PyHASH_BITS是61(64位系统)或31(32位系统)(在此定义)
因此,在64位系统上,内置hash函数看起来像这样:
def hash(number):
return number % (2 ** 61 - 1)
Run Code Online (Sandbox Code Playgroud)
这就是为什么对于小整数,您拥有相同的值,而例如hash(2305843009213693950)return 2305843009213693950和hash(2305843009213693951)return0