Junior — Middle
What is the main purpose of the __hash__ method in Python and why is it necessary when working with objects?
sobes.tech AI
Answer from AI
The __hash__ method in Python returns an integer value (hash) of an object, which is used for quick comparison and lookup of objects in hash tables, such as in sets (set) and dictionaries (dict).
The main task of __hash__ is to provide a unique and immutable identifier for the object during its lifetime, so that objects can be efficiently used as keys in dictionaries or elements of a set.
It is important that if an object overrides the __eq__ method, then to ensure correct hashing, __hash__ should also be overridden so that objects considered equal have the same hash.
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2) # True
print(hash(p1) == hash(p2)) # True
s = {p1}
print(p2 in s) # True
Without a proper __hash__, objects cannot be used as keys in sets and dictionaries.