Practice Note-the non-Hash object in python is set to a hash object, note-python
Before this article, I have translated the official python3.3 hashable object document. You can refer to it first:
Practice Note-what is a hash object in python? What is hashable object in python?
Prerequisites:
When defining a class, if we need to rewrite the _ eq _ function of the class, we should note that it will become a non-Hash object, that is to say, if you put it in a hash assembly, an error is reported.
>>> 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 == bTrue>>> dic = {a:1}Traceback (most recent call last): File "<ipython-input-6-8bf0323d7544>", line 1, in <module> dic = {a:1}TypeError: unhashable type: 'A'
But what if we define this class to rewrite the _ eq _ function and set it to a hash object? The official documents have already been described in detail. We only need to add_ Hash _ = object. _ hash __You can.
>>> 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 == bTrue>>> dic = {a:1}>>>
So the question is, if we want to use B as the key value to find the corresponding data in dic, can we succeed?
>>> Dic [a] 1 >>> dic [B] # key value error Traceback (most recent call last): File "<ipython-input-13-5e085ba4c448>", line 1, in <module> dic [B] KeyError: <__ main __. A object at 0x103b77610 >>>. _ hash _ () # Here we find that the hash values of a and B are different from 272332629> B. _ hash _ () 272332641 >>> hash (a) = hash (B) False
From the code above, we know that the search for a key value in the hash set is compared against the hash value of the key value. Even if _ eq _ is rewritten, the corresponding key value search in the hash set is not affected.