在Python文档中,我们可以阅读__hash__
函数:
The only required property is that objects which compare equal have the same hash value.
我有一个对象,它可以等于同一类型的其他对象,也可以等于字符串:
class MyClass:
def __eq__(self, other):
if isinstance(other, str):
return self.x == other
if isinstance(other, MyClass):
return id(self) == id(other)
return False
有了这个__eq__
函数,我如何定义一个有效的__hash__
函数?你知道吗
警告:这里,MyClass()
对象是可变的,self.x
可能会更改!你知道吗
不能定义一致的哈希。首先,您的类没有一致地定义
__eq__
;不能保证如果x == y
和y == z
,那么x == z
。第二,你的对象是可变的。在Python中,可变对象不应该是可散列的。你知道吗断开
==
的示例:相关问题 更多 >
编程相关推荐