python - 如何使我的类可用作字典键?

标签 python dictionary key

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/

相关文章:

swift - 在使用字典时映射列表?

javascript - 使用 JavaScript 查找关联数组中的键

python - 如何在 python 中访问切片对象的元素

python - 将函数链接到模型条目

python - 为什么我的 Scrapy 蜘蛛没有按预期运行?

python - 如何使用Python在两个不同的图像中找到两个相同的像素(颜色值)

python - SSD 与 tmpfs 速度

dictionary - Groovy:在 map 列表中按键查找/返回 map 的值

c# - 在 C# 中使用组合键触发按钮单击事件

android - 使用 keystore 确认 APK 身份