我想根据我的对象的名称检查它是否已经存在于词典中 name . 我当前的实现没有返回预期的结果,所以我肯定在这里遗漏了一些东西。
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__() 实施?
__hash__()
你还需要添加相等的dunder。从 documentation 属于 __hash__ __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