Before this article, I have specifically translated the official python3.3 of the hash object document, you can first refer to:
Internship-python What is a hash object in a small memory? What's Hashable object in Python?
Pre-Knowledge:
When defining a class, if we need to overwrite the __eq__ function of the class, it is important to note that it will become a non-hash object, that is, if you put it in a hash-assembly report error
>>> 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}TRACEB ACK (most recent call last): File ' <ipython-input-6-8bf0323d7544> ', line 1, in <module> dic = {A:1}ty Peerror:unhashable type: ' A '
But what if we define the class that needs to rewrite the __eq__ function and set it as a hash object? The official documentation has been described in detail, we only need to add __hash__ = object.__hash__ in the class variable.
>>> 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}>&G T;>
So the question is, if we want to use B as the key value to find the corresponding data in DIC can be successful?
>>> dic[a]1>>> Dic[b] #提示键值错误Traceback (most recent): 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
From the code above we know that the lookup of a key value in a hash set is compared against the hash value of that key value. Even if we rewrite __eq__, it will not affect the lookup of the corresponding key value in the hash set.
The non-hash object in the internship-python is set to a hash object