all Python 3OOPfunction
__eq__
magic methods
The method behind ==. Without it two objects are equal only when they are the same object, as with is.
Syntax
def __eq__(self, other): ...
Defining __eq__ removes __hash__: instances can no longer go into a set or serve as dict keys until a __hash__ consistent with equality is defined too. Python 3 derives != itself by inverting __eq__. For a foreign type return NotImplemented rather than False, so Python asks the other operand.
Examples
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
print(Point(1, 2) == Point(1, 2)) # → True
print(Point(1, 2) != Point(3, 4)) # → True — != выведен из __eq__
print(Point.__hash__) # → None — без __hash__ в set не положить
See also
Open in the full glossarydocs.python.orgReport an inaccuracy