自定义哈希:对象在字典中吗?

Custom hash: is object in a dictionary?

我想根据它 name 检查我的对象是否已经存在于字典中。我目前的实施没有 return 预期的结果,所以肯定我在这里遗漏了一些东西。

我的class:

@dataclass
class Foo:
    name: str
    number: int
        
    def __hash__(self):
        return hash(self.name)

和代码:

d = {}
foo1 = Foo('foo1', 1)
foo2 = Foo('foo2', 2)
foo3 = Foo('foo1', 3)
foo4 = Foo('foo4', 1)
d[foo1] = foo1
d[foo2] = foo2

print(f'Is foo3 in d? {foo3 in d}') # prints: "Is foo3 in d? False" Expected True (NOK)
print(f'Is foo4 in d? {foo4 in d}') # prints: "Is foo4 in d? False" Expected False (OK)
print(f'foo1 hash: {foo1.__hash__()}') # 4971911885166104854
print(f'foo3 hash: {foo1.__hash__()}') # 4971911885166104854

除了 __hash__() 实施,我还需要其他任何东西吗?

您还需要添加平等双打。来自 documentation of __hash__ and __eq__:

If a class does not define an eq() method it should not define a hash() operation either;

添加 __eq__ 后,出现以下行为。

    def __eq__(self, x):
        return hash(self) == hash(x)

在 运行 程序中,我得到:

Is foo3 in d? True
Is foo4 in d? False
foo1 hash: -4460692046661292337
foo3 hash: -4460692046661292337