Py学习  »  Python

Python:为什么散列函数不是确定性的?

claudioz • 4 年前 • 732 次点击  

我正在开发一个程序 蟒蛇3.6 我有一个问题:如果我使用确定性 hash 函数(来自语言的标准库)在同一个对象上,导致输出的字符串(运行后)在某些运行中是不同的! 例如:

class Generic:
    def __init__(self, id, name, property):
        self.id = id 
        self.name = name
        self.property = property


def main():
    my_object = Generic(3,'ddkdjsdk','casualstring')    
    print(hash(my_object))

我希望输出始终相同(确定性),但不幸的是,控制台上出现了不同的字符串: 8765256330262、-922336326451786864、-9223363262437648366及其他。。。 为什么会这样?我想在我的应用程序中保证这个函数的决定论!我该如何解决这个问题?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50903
 
732 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Luke
Reply   •   1 楼
Luke    5 年前

在这种情况下,可能最容易定义自己的 __eq__ 功能和 __hash__ 功能。这将每次为您返回相同的哈希值:

class Generic:
    def __init__(self, id, name, property):
        self.id=id
        self.name = name
        self.property = property

    def __eq__(self, other):
        assert self.__class__ == other.__class__, "Types do not match"
        return self.id == other.id and self.name == other.name and self.property == other.property

    def __hash__(self):
        return hash ( (self.id, self.name, self.property) )

这还将使等效对象的散列相等,以及:

>>>obj = Generic(1, 'blah', 'blah')
>>>obj2 = Generic(1, 'blah', 'blah')
>>>obj == obj2
True
>>>hash(obj) == hash(obj2)
True

希望能有帮助!