The !=
operator invokes the __ne__
special method. Classes that define __eq__
should also define a __ne__
method that does the inverse.
The typical pattern for providing __eq__
, __ne__
, and __hash__
looks like this:
class SomeClass(object):
# ...
def __eq__(self, other):
if not isinstance(other, SomeClass):
return NotImplemented
return self.attr1 == other.attr1 and self.attr2 == other.attr2
def __ne__(self, other):
return not (self == other)
# if __hash__ is not needed, write __hash__ = None and it will be
# automatically disabled
def __hash__(self):
return hash((self.attr1, self.attr2))