Recommended way to implement __eq__ and __hash__
Answering my own question. It seems one way of performing this is to define an auxillary __members
function and to use that in defining __hash__
and __eq__
. This way, there is no duplication:
class MyClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __members(self):
return (self.a, self.b)
def __eq__(self, other):
if type(other) is type(self):
return self.__members() == other.__members()
else:
return False
def __hash__(self):
return hash(self.__members())