Internship-python What is a hash object in a small memory? What's Hashable object in Python?

Source: Internet
Author: User

No more nonsense. Direct offerings on python3.3x documents: (original link)

  object. __hash__ ( self )

called by built-in function hash () and for operations on members of Hashed collections including set , frozenset , and < Span class= "Pre" >dict . __hash__ () should return an integer. The only required property was that objects which compare equal has the same hash value; It's advised to somehow mix together (e.g. using exclusive OR) the hash values for the components of the object that also Play a part in comparison of objects.

A hash object is an object that has an __hash__ (self) built-in function. Executing this function on a hash object will return an integer. The only condition in which a hash object can judge equality is that the hash values are equal. If our object has multiple property values, we will use a method, such as a logical operation XOR, to compare its property values together. (if not, please tell me, thank you!) )

If A class does not define an__eq__ ()Method It should not define a__hash__ ()Operation either; If it defines__eq__ ()But not__hash__ (), its instances is not being usable as items in hashable collections. If A class defines mutable objects and implements an__eq__ ()method, it should not implement__hash__ (), since the implementation of Hashable collections requires that a key's hash value is immutable (if the object ' s hash val UE changes, it'll be in the wrong hash bucket).

If a type definition does not define a __eq__ () function, then it should not define __HASH__ (), because if it defines __eq__ and does not define __HASH__, its instances will not be valid in a hash set (for example, in a dictionary/collection type). If a type defines a mutable object and defines the __eq__ method, it should not define the __hash__ method, because the hash value of the element in the hash set is required to be constant (if the hash value of an object instance changes, then he will go to the wrong hash table: )。

user-defined classes have __eq__ () and __hash__ () methods by default; With them, all objects compare unequal (except with themselves) and x.__ Hash__ () returns an appropriate value such that x == y implies both that x is y and hash (x) == hash (y) .

There are default __eq__ and __hash__ methods in the user-defined class; With it, all object instances are unequal (unless you compare yourself with yourself) x = = y The is compared with this equivalent hash (x) = = Hash (y) .

A class that overrides __eq__ () And does not define __hash__ () would have Its __hash__ () implicitly set to none . When the __hash__ () method of a class is TT class= "docutils literal" >none , instances of the class would raise an appropriate typeerror when a program attempts to retrieve their hash Value, and would also be correctly identified as unhashable when checking i Sinstance (obj, collections. hashable ).

This means that if we define a type that defines only __eq__ and does not define __hash__, then his __hash__ () is implicitly set to none, and if this type of hash value is required in a case, the program will error. Please see the following code for details:

>>>classA: ...def __eq__(self, Other): ...returnTrue ...>>> A =A ()>>>ImportCollections>>> Isinstance (A, collections. hashable)#found that it is not a hash objectFalse>>> A.__hash__>>> A.__hash__() Traceback (most recent): File"<ipython-input-20-0fddd0562e01>", Line 1,inch<module>A.__hash__() TypeError:'Nonetype'Object is  notCallable

Then look down at the document

If A class that overrides __eq__ () needs to retain the implementation of __hash__ () from a parent class, The interpreter must is told this explicitly by setting __hash__ = <parentclass>.__hash__.

If an object that overrides the __eq__ method needs to preserve the __hash__ property, then we need to add the statement in the type setting __hash__ = <parentclass>.__hash__

Please look at the code

class A:      ... __hash__ = object. __hash__ ...      def __eq__ (self, Other): ...          return True ...      >>> a = A ()>>> A.__hash__'__hash__' of a Object at 0x7f21029cfa10>>>> set ([a,2,3]) {<__main__. A object at 0x7f21029cfa10>, 2, 3}

If A class that does not override __eq__ () wishes to suppress hash support, it should include __hash__ = None In the class definition. A class which defines its own __hash__ () so explicitly raises a TypeError would be incorrectly ident Ified as hashable by an isinstance (obj, collections. hashable) call.

If a type definition needs to delete the __hash__ attribute, then we can write this in the class variable __hash__ = None

After reading it is still a little excited, today because of an accidental reason, exposed to so many python knowledge. Really is very happy Ah!

However, I also found that __eq__ __hash__ these two methods can not move freely, if I need to rewrite one of them must carefully consider the possible situation, in order to avoid problems.

Internship-python What is a hash object in a small memory? What's Hashable object in Python?

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.