Python hash() 无法处理长整数?
我定义了一个类:
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()函数给出负整数?
I defined a class:
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
Why, in the doctest, hash() function gives a negative integer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它似乎仅限于 32 位。通过阅读这个问题,您的代码可能已经在64 位机器(具有这些特定值,因为结果适合 64 位)。
内置
哈希
函数的结果依赖于平台并受限于本机字大小。如果您需要确定性的跨平台哈希,请考虑使用hashlib
模块。It appears to be limited to 32-bits. By reading this question, it looks like your code might have produced the expected result on a 64-bit machine (with those particular values, since the result fits in 64 bits).
The results of the built-in
hash
function are platform dependent and constrained to the native word size. If you need a deterministic, cross-platform hash, consider using thehashlib
module.请参阅
object.__hash__
请注意
在您的情况下,预期 12544897317L 是一个长整型对象,
Python 通过(12544897317 & 0xFFFFFFFF) - (1<<32) 派生出 32 位整数 -340004569 - (1<<32)
Python 通过 hash(12544897317L) 推导出 32 位整数,结果为 -340004569
算法如下:
See
object.__hash__
Notice that
In your case, expected 12544897317L is a long integer object,
Python derived the 32-bit integer -340004569 by(12544897317 & 0xFFFFFFFF) - (1<<32)
Python derived the 32-bit integer by hash(12544897317L), which results -340004569
The algorithm is something like this:
因为哈希函数的目的是获取一组输入并将它们分布在一系列键上,所以这些键没有理由必须是正整数。
事实上,Python 的哈希函数返回负整数只是一个实现细节,并且必然仅限于长整型。例如 hash('abc') 在我的系统上是负数。
Because the purpose of a hash function is to take a set of inputs and distribute them across a range of keys, there is no reason that those keys have to be positive integers.
The fact that pythons hash function returns negative integers is just an implementation detail and is necessarily limited to long ints. For example hash('abc') is negative on my system.