首页 > 解决方案 > 自定义哈希:对象在字典中吗?

问题描述

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

我的课:

@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__()吗?

标签: pythonhash

解决方案


您还需要添加平等 dunder。从and的文档中:__hash____eq__

如果一个类没有定义一个eq () 方法,它也不应该定义一个hash () 操作;

添加后__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

推荐阅读