Internship-python The non-hash object is set to a hash object

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.