Sobes.tech
Junior — Middle

Explain what an object that can be hashed is, and what features it should have.

sobes.tech AI

Answer from AI

An object that can be hashed in Python is an object that has a defined __hash__() method returning an integer hash value. Such an object must be immutable (unchangeable) so that its hash remains constant during its lifetime.

Features of a hashable object:

  • Immutability: the object's fields should not change, otherwise the hash becomes invalid.
  • Implementation of __hash__: the method should return an integer.
  • Implementation of __eq__: objects considered equal by __eq__ should have the same hash.

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))

p = Point(1, 2)
print(hash(p))

Such an object can be used as a key in dictionaries or as an element of a set.