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

2024-07-08 10:43:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

因此,当我从散列打印时,我得到93792909800245310080479536979750034401273674738852415427366199722413460820022, 但是当我打印hashkey时,我得到了377513311013302392?为什么?

EDIT:所以我显式地调用了hash(),得到了我期望的数字,但是由于我重写了hash(),我不应该从hash()得到相同的值吗


Tags: 对象函数selfdefvalhashclassint
1条回答
网友
1楼 · 发布于 2024-07-08 10:43:38

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

相关问题 更多 >

    热门问题