Middle
What needs to be implemented in a class to make it hashable?
sobes.tech AI
Answer from AI
To make a class in Python hashable, you need to implement two methods: __eq__ and __hash__.
__eq__(self, other): This method defines the equality comparison operation (==). It should accept another objectotherand returnTrueif the objects are equal, andFalseotherwise.__hash__(self): This method should return an integer hash value of the object. Ifa == bis always true, thenhash(a)should also be equal tohash(b). The hash should remain constant during the lifetime of the object.
If you implement only __eq__ but not __hash__, Python will automatically assign __hash__ the value None, making the object unhashable. If you implement only __hash__ but not __eq__, Python will use the default comparison implementation (by identifier), which can lead to incorrect behavior when using objects in hashable collections.
Classes containing mutable attributes generally should not be hashable, as changing an attribute after computing the hash violates the invariant that the hash of an object remains constant during its lifetime.
Example:
class MyImmutableClass:
def __init__(self, value):
self.value = value # Attribute that does not change after initialization
def __eq__(self, other):
if not isinstance(other, MyImmutableClass):
return NotImplemented
return self.value == other.value
def __hash__(self):
return hash(self.value)