python - 自定义哈希:对象在字典中吗?
问题描述
我想检查我的对象是否已经存在于基于它的字典中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__()
吗?
解决方案
您还需要添加平等 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
推荐阅读
- python - 如何在访问返回值等属性时停止调用方法
- mysql - WHERE + Insert Into 中的 MySQL IF 子句
- excel - Excel 中的唯一范围不返回唯一记录,而是返回所有其他记录
- javascript - JSON 解析错误:意外的标识符“对象”
- r - 如何防止 R 按字母顺序排列 ggplot 中的数据并指定绘制数据的顺序(提供的数据 + 代码 + 图表)?
- ios - Switch 语句而不是大量的 if 语句
- c++ - “操作员+=”行为异常的定义
- jakarta-ee - 无法识别的字段...未标记为可忽略,EE8 / Jakarta EE
- sql - 在 SQL 块中获取 ora-01858
- c# - 表单不返回值 ASP.NET Core 2.2