python - 当一个对象可以等于不同类型的对象时,如何定义 __hash__ ?

标签 python hash

在 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 == yy == z,则x == z。其次,你的对象是可变的。在 Python 中,可变对象不应该是可哈希的。

If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

损坏的==示例:

x = MyClass('foo')
y = 'foo'
z = MyClass('foo')

x == y # True
y == z # True
x == z # False

关于python - 当一个对象可以等于不同类型的对象时,如何定义 __hash__ ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20832171/

相关文章:

python - 使用 scipy.sparse.linalg 中的 svds 按降序排序的奇异值

python - django - 如何使用 request.FILES 对发布请求进行单元测试

sql - 如何扫描两个查询之间的差异?

ruby-on-rails - Rails session 数据 - 存储在哈希中

java - 如何编码和缩短哈希以保证 URL 安全?

python - pyqtgraph - 导入错误 : No module named pyqtgraph

python - Django Admin 中的欧洲日期输入

c++ - 实现哈希表

amazon-web-services - 在Delphi 10.3中发出AWS Signature Version 4请求,将Python代码移植到Delphi

python - matplotlib stepfilled 直方图在 xubuntu 的值 10^-1 处中断