我什么时候需要在我自己的对象上添加哈希,例如python数据类?
我经常发现自己处于两种情况之一。我现在有一个类,是标准类
class myClass:
def __init__(self, x):
self.x = x
或数据级别
@dataclass(frozen=True)
class myClass:
x: float
,我想要的就是能够将这两个类作为键存储在词典中,以便hash在对象本身的瞬间上当(仅当)我使用我存储为键的对象的瞬间查找时(仅当)我查找。
我已经在线阅读了一些,让我感到困惑的是__ eq __
操作员。我不知道为什么在这里很重要。我想要的只是字典要通过其ID记住该对象。因此,我的问题是
- 我需要添加
def __hash __(self):返回id(self)
返回到上面的两个对象中的任何一个,还是总是隐含的? - 我需要添加
__ eq __
吗?
I find myself in one of two situations very often. I have a class, either a standard class
class myClass:
def __init__(self, x):
self.x = x
or a dataclasss
@dataclass(frozen=True)
class myClass:
x: float
Now, all I want is to be able to store these two classes as keys in a dictionary, such that the hash is on the instant of the object itself, so look-up will work if (and only if) I look-up using the exact same instant of the object that I stored as key.
I've read online a bit, and what confuses me is the __eq__
operator. I have no idea why that is relevant here. All I want is for dictionaries to remember the object by its id. So, my questions are
- do I need to add
def __hash__(self): return id(self)
to any of those two objects above, or is this always implicit? - do I need to add
__eq__
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论