我什么时候需要在我自己的对象上添加哈希,例如python数据类?

发布于 2025-01-21 01:45:12 字数 519 浏览 3 评论 0原文

我经常发现自己处于两种情况之一。我现在有一个类,是标准类

class myClass:
    def __init__(self, x):
        self.x = x

或数据级别

@dataclass(frozen=True)
class myClass:
    x: float

,我想要的就是能够将这两个类作为键存储在词典中,以便hash在对象本身的瞬间上当(仅当)我使用我存储为键的对象的瞬间查找时(仅当)我查找。

我已经在线阅读了一些,让我感到困惑的是__ eq __操作员。我不知道为什么在这里很重要。我想要的只是字典要通过其ID记住该对象。因此,我的问题是

  1. 我需要添加def __hash __(self):返回id(self)返回到上面的两个对象中的任何一个,还是总是隐含的?
  2. 我需要添加__ 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

  1. do I need to add def __hash__(self): return id(self) to any of those two objects above, or is this always implicit?
  2. do I need to add __eq__?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文