蟒蛇:我的类作为字典键.如何? [英] python: my classes as dict keys. how?
本文介绍了蟒蛇:我的类作为字典键.如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
如何正确执行此操作?
how can I implement this without error?
FFFUUU,错误为:
我试图用另一个具有相同内容的A()BUT实例来获取d[elem2]
(而不是elem
). (对我感到羞耻)
仍然..我该怎么做?重新定义__hash__
?
FFFUUU, the error was:
I tried to get d[elem2]
(not elem
) with another instance of A() BUT with the same content. (shame on me)
Still.. how can I do this? redefine __hash__
?
推荐答案
是的,您需要重新定义__hash__()
:
The answer is yes, you need to redefine __hash__()
:
>>> 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__
的默认实现只是简单的标识,因此,如果要使其更复杂,则需要显式定义.
As explained in another comment default implementation of __hash__
is just simple identity, so if you want to make it more sophisticated, you need to define it explicitly.
这篇关于蟒蛇:我的类作为字典键.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文