gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:28:36 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com