Xie*_*Xie 9 python hash integer
我定义了一个类:
class A:
''' hash test class
>>> a = A(9, 1196833379, 1, 1773396906)
>>> hash(a)
-340004569
This is weird, 12544897317L expected.
'''
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
def __hash__(self):
return self.a * self.b + self.c * self.d
为什么在doctest中,hash()函数给出一个负整数?
请注意
在版本2.5中更改:
__hash__()现在也可以返回一个长整数对象; 然后从该对象的散列派生32位整数.
在您的情况下,预期12544897317L是一个长整数对象,
Python派生出32位整数-340004569 (12544897317 & 0xFFFFFFFF) - (1<<32)
Python通过hash(12544897317L)派生了32位整数,结果为-340004569
算法是这样的:
def s32(x):
x = x & ((1<<32)-1)
if x & (1<<31):
return x - (1<<32)
else:
return x
def hash(x):
h = 0
while x:
h += s32(x)
x >>= 32
return h
Run Code Online (Sandbox Code Playgroud)