gpt4 book ai didi

python - 重写的哈希函数的计算值和返回值不同

转载 作者:行者123 更新时间:2023-12-01 02:03:56 24 4
gpt4 key购买 nike

我为一个对象创建了一个哈希函数。我遇到的问题是我在哈希函数中创建的值不是从函数返回的值。

class someClass():

def someClass(str1, str2, str3):
self.str1 = str1
self.str2 = str2
self.str3 = str3
...
def __hash__(self):
hash_val = int(sha256((self.str1+ self.str2
+ self.str3).encode('utf-8')).hexdigest(), 16)
# print's 937929098002453100804....
print(hash_val)
return hash_val
...

testClass = someClass('test', 'testClass', 'testCase')
hashKey = hash(testClass)
# print's 377513311013302392
print(hashKey)

因此,当我从 hash() 打印时,我得到 93792909800245310080479536979750034401273674738852415427366199722413460820022,但是当我打印 hashkey 时,我得到 377513311013302392?为什么?

编辑:所以我明确地调用了hash(),并得到了我期望的数字,但是由于我覆盖了hash(),我不应该从 hash() 中获得相同的值吗?

最佳答案

来自the docs :

Note hash() truncates the value returned from an object’s custom hash() method to the size of a Py_ssize_t. This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds.

93792909800245310080479536979750034401273674738852415427366199722413460820022 远远高于这些限制。

试试这个:

class C():

def __hash__(self):
return 93792909800245310080479536979750034401273674738852415427366199722413460820022

a = C()
b = C()

print(hash(a))
print(hash(b))

输出:

377513311013302392
377513311013302392

关于python - 重写的哈希函数的计算值和返回值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com