使用实例作为键时__hash__未被调用

时间:2016-02-18 01:00:08

标签: python dictionary hash key built-in

我搜索了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 字符串。我做错了什么?

1 个答案:

答案 0 :(得分:1)

这是因为密钥是对象而您没有覆盖默认的__repr__

您需要将其添加到testFoo类。

def __repr__(self):
    return self.x