Python hash with if cases
Python hash with if cases
我对 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不为空,则returnself.gammas或self.gammabars等的哈希值
但是如果我现在开始我的程序,我会得到:
TypeError: __hash__ method should return an integer
那么你知道如何解决这个问题吗?
当您调用hash(instance)
时,您的self.gammas
或self.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.gammas
和 self.gammabars
值。
使用元组哈希的方法:
return hash((self.gammas, self.gammabar))
我对 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不为空,则returnself.gammas或self.gammabars等的哈希值
但是如果我现在开始我的程序,我会得到:
TypeError: __hash__ method should return an integer
那么你知道如何解决这个问题吗?
当您调用hash(instance)
时,您的self.gammas
或self.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.gammas
和 self.gammabars
值。
使用元组哈希的方法:
return hash((self.gammas, self.gammabar))