Curriculum
In Python, the __hash__
method is a special method that is used to define a unique integer that represents an object of a class. This method is called when the hash()
function is used on an object of the class. The __hash__
method should return an integer that is unique for each object of the class.
Here’s an example of how the __hash__
method can be used in Python:
class Point: def __init__(self, x, y): self.x = x self.y = y def __hash__(self): return hash((self.x, self.y)) p1 = Point(1, 2) p2 = Point(1, 2) p3 = Point(2, 3) print(hash(p1)) # Output: 3713081631934410656 print(hash(p2)) # Output: 3713081631934410656 print(hash(p3)) # Output: 6465470146696584693
In this example, we define a Point
class with two attributes: x
and y
. We also define a __hash__
method that generates a unique integer that represents the Point
object based on its x
and y
attributes.
When we create two Point
objects with the same x
and y
values and apply the hash()
function to them, the __hash__
method is called and generates the same integer value for both objects. This allows us to use Point
objects as keys in dictionaries and sets.
Note that the __hash__
method should return an integer that is consistent with the __eq__
method. That is, if two objects are considered equal by the __eq__
method, they should have the same hash value. This is because when two objects are compared for equality using the ==
operator, their hash values are first compared to quickly determine if they are different.