【问题标题】:Why isn't the hash function deterministic?为什么哈希函数不是确定性的?
【发布时间】:2019-08-01 18:40:22
【问题描述】:

我正在使用 Python 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、-9223363264515786864、-9223363262437648366等... 为什么会发生这种情况?我想在整个应用程序中保证此功能的确定性!我该如何解决这个问题?

【问题讨论】:

标签: python object hash deterministic


【解决方案1】:

在这种情况下,定义自己的__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

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2011-06-04
    • 2018-03-31
    • 2015-04-29
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多