hash() method in python can match all immutable objects to unique hash value. However, I cannot understand the behavior of hash() method for objects of user-defined classes. Some of the resources say that if user-defined class do not contain __hash__()
and __eq__()
methods, that object cannot be hashed. On the other hand, the others claim the opposite one.
In other words, what is the role of __eq__()
and __hash__()
methods in order to hash custom objects ?
Basically, 'hash' should be quick, and act as a "triage" calculation to quickly know if two objects are not equal.
The 'eq'(uality) function is the function that tells if the objects are definitely equal or not. Maybe this function has to perform a lot of checks ( for instance if you want to define the equality of your objects by the equality of every member fields).
The purpose of these two functions is to have a quick way of saying "no, they are not equal" (the hash function), since the comparisons are often used a lot and most often two objects are not "equal".
Instead of executing a lot of "eq" functions, you execute a lot of quick "hash" functions, and if both the hashes match, the "eq" is executed to confirm the equality or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With