Junior — Middle
What special methods in Python allow managing object behavior when working with hashing?
sobes.tech AI
Answer from AI
In Python, special methods __hash__() and __eq__() are used to control the behavior of objects during hashing.
-
__hash__(self)— should return an integer hash value of the object. It is used when the object is placed in hash tables, such as in sets (set) or as dictionary keys (dict). -
__eq__(self, other)— defines the logic for comparing objects for equality. It is important that objects considered equal (__eq__returnsTrue) have the same hash (__hash__).
If you override __eq__ but not __hash__, the object becomes unhashable (cannot be used as a key in a dictionary).
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
p1 = Point(1, 2)
p2 = Point(1, 2)
print(hash(p1), hash(p2)) # same hashes
print(p1 == p2) # True
s = {p1}
print(p2 in s) # True
Therefore, to work correctly with hashing, both methods should be implemented, considering their relationship.