我想使自定义对象可以哈希(通过酸洗).我可以找到__hash__Python 2.x的算法(参见下面的代码),但它明显不同于 Python 3.2的哈希(我想知道为什么?).有谁知道如何__hash__在Python 3.2中实现?
#Version: Python 3.2
def c_mul(a, b):
#C type multiplication
return eval(hex((int(a) * b) & 0xFFFFFFFF)[:-1])
class hs:
#Python 2.x algorithm for hash from http://effbot.org/zone/python-hash.htm
def __hash__(self):
if not self:
return 0 # empty
value = ord(self[0]) << 7
for char in self:
value = c_mul(1000003, value) ^ ord(char)
value = value ^ len(self)
if value == -1:
value = -2
return value
def main():
s = ["PROBLEM", "PROBLEN", "PROBLEO", "PROBLEP"]#, …Run Code Online (Sandbox Code Playgroud)