实习小记-python中不可哈希对象设置为可哈希对象

在这篇之前,我又专门翻译过官方python3.3的可哈希对象文档,大家可以先参考一下:

实习小记-python中可哈希对象是个啥?what is hashable object in python?

预备知识:

  在定义一个类时,如果我们需要改写该类的__eq__函数,特别要注意的是它将会变为不可哈希对象,也就是说如果你将它放到哈希集会报错误

>>> class A:
...     def __init__(self, x):
...         self.x = x
...     def __eq__(self, other):
...         return self.x == other.x
...
>>> a = A(1)
>>> b = A(1)
>>> a == b
True
>>> dic = {a:1}
Traceback (most recent call last):
  File "<ipython-input-6-8bf0323d7544>", line 1, in <module>
    dic = {a:1}
TypeError: unhashable type: 'A'

   可是如果我们定义的这个类既需要重写__eq__函数也需要把它设定为可哈希的对象这该怎么办呢?官方文档里面已经详细描述了,我们只需在类变量中加上__hash__ = object.__hash__ 即可。

>>> class A:
...     __hash__ = object.__hash__
...     def __init__(self, x):
...         self.x = x
...     def __eq__(self, other):
...         return self.x == other.x
...
>>> a = A(1)
>>> b = A(1)
>>> a == b
True
>>> dic = {a:1}
>>>

   

  那么问题来了,如果我们想用b为键值查找dic中对应的数据可以成功吗?

>>> dic[a]
1
>>> dic[b] #提示键值错误
Traceback (most recent call last):
  File "<ipython-input-13-5e085ba4c448>", line 1, in <module>
    dic[b]
KeyError: <__main__.A object at 0x103b77610>
>>> a.__hash__() #这里我们发现a和b的哈希值是不一样的
272332629
>>> b.__hash__()
272332641
>>> hash(a) == hash(b)
False

   从上面的代码我们知道,在哈希集中对某个键值的查找是针对该键值的哈希值做比较的。即使我们重写了__eq__也不会影响到哈希集中对应键值的查找。

原文地址:https://www.cnblogs.com/Blaxon/p/4719208.html