class A():
def __init__(self, data=''):
self.data = data
def __str__(self):
return str(self.data)
d = {}
elem = A()
d[elem] = 'abc'
elem2 = A()
print d[elem2] # KeyError
# actually elem2! was used not elem
我怎样才能不出错地实现它?
我试图用另一个 A() 实例获取 d[elem2]
(不是 elem
),但内容相同。
最佳答案
答案是肯定的,需要重新定义__hash__()
和__eq__()
:
>>> class A(object):
... def __init__(self, data=''):
... self.data = data
... def __eq__(self, another):
... return hasattr(another, 'data') and self.data == another.data
... def __hash__(self):
... return hash(self.data)
...
>>> a1, a2, a3 = A('foo'), A('foo'), A('bar')
>>> d = {a1: 'foo'}
>>> d[a1]
'foo'
>>> d[a2]
'foo'
>>> d[a3]
Traceback (most recent call last):
File "", line 1, in
KeyError: __main__.A object at 0x927d0>
正如在另一条评论中所解释的,__hash__
的默认实现只是简单的标识,所以如果你想让它更复杂,你需要明确地定义它。
关于python - 如何使我的类可用作字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5221236/