【问题标题】:Python hash with if casesPython hash with if case
【发布时间】:2018-12-15 10:53:15
【问题描述】:

我有一个关于 Python 的 hash(self) 函数的问题。

所以在我的方法中,我有以下代码片段

def __init__(self, upper1, lower1, upper2, lower2):
    self.phase = 1
    self.gammas = frozenset()
    self.gammabars = frozenset()

def __hash__(self):
    if self.gammas:
        return hash(self.gammas)
    elif self.gammabars:
        return hash(self.gammabars)

所以我想说:

如果 self.gammas 不为空,则返回 self.gammas 或 self.gammabars 等的 hashvalue。

但是如果我现在开始我的程序,我会得到:

TypeError: __hash__ method should return an integer

那么你知道如何解决这个问题吗?

【问题讨论】:

  • 请显示运行程序并重现问题所需的所有代码。
  • @KlausD。嗯,问题是,代码很长。

标签: python hash set hashtable


【解决方案1】:

当您拨打hash(instance) 时,您的self.gammasself.gammabars 都不能是True。您可以尝试添加一个 else 案例:

def __hash__(self):
    if self.gammas:
        return hash(self.gammas)
    elif self.gammabars:
        return hash(self.gammabars)
    else:
        return hash(something)
        # or
        raise ValueError('gammas and gammabars are not valid.')

或调试您的代码以确认 self.gammasself.gammabars 值。

【讨论】:

  • 嗯,谢谢,所以如果我添加 if self.gammas != {}: return hash(self.gammas) 就可以了。但奇怪的是,它不能以相反的方式工作。
  • @Armani42 in the other way around 是什么意思?可以举个例子吗?
  • 请注意,dict 是不可散列的。所以 hash(dict_instance) 会引发TypeError: unhashable type: 'dict'
  • 是的,所以如果我说 if self.gammas: 我得到错误,如果我说 != {} 那么它可以工作,我真的不知道为什么......
  • @Armani42 哦,我明白了。如果你的条件是if self.gammas != {},表示frozenset() != dict(),如果是空的frozenset,结果为True。但是如果你的条件是if self.gammas,那就是bool(frozenset()),如果是空的frozenset,结果就是False。您可以通过以下方式对其进行测试:print(frozenset() != {}) print(bool(frozenset()))
【解决方案2】:

使用元组方法的哈希:

return hash((self.gammas, self.gammabar))

【讨论】:

  • 但我没有包含 gammas 和 gammabars 的元组。
  • 返回元组的哈希并不重要。
  • 啊,请注意,返回hash((self.gammas, self.gammabar))会导致一些意想不到的结果。例如,如果self.gammasnot empty,则@Armani42 想要返回hash(self.gammas)。大多数时候它没有任何问题,然而,一些特殊情况,想象一下如果 self.gammas 是一样的,但是 self.gammabars 已经改变了,hash((self.gammas, self.gammabars)) 会变得不同。但在这种情况下,应该是一样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2020-03-29
  • 2017-03-22
相关资源
最近更新 更多