【问题标题】:__hash__ not being called when using instance as key使用实例作为键时未调用 __hash__
【发布时间】:2016-05-29 23:48:27
【问题描述】:

我搜索了 SO 并发现了很多关于这个主题的问题,我尝试重新创建已接受的答案,但我无法复制显示的输出。

>>> class testFoo(object):
...     def __init__(self,x):
...         self.x = x
...     def __eq__(self, other):
...         return hash(self.x) == other
...     def __hash__(self):
...         return hash(self.x)
...
>>> d = {}
>>> x = testFoo("a")
>>> d[x] = 1
>>> d
{<__main__.testFoo object at 0x7f6d9ccc5550>: 1}
>>> hash(x)
12416037344
>>> hash("a")
12416037344
>>>

当我在上面键入“d”时,我期望看到的是键“a”,而不是对象的 repr 字符串。我做错了什么?

【问题讨论】:

    标签: python dictionary hash key built-in


    【解决方案1】:

    那是因为关键是对象并且你没有覆盖默认的__repr__

    您需要将此添加到testFoo 类。

    def __repr__(self):
        return self.x
    

    【讨论】:

    • 哇!谢谢!放在那里,它按预期工作。
    猜你喜欢
    • 2021-12-17
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    相关资源
    最近更新 更多