Skip to content Skip to sidebar Skip to footer

Recommended Way To Implement __eq__ And __hash__

The python documentation mentions that if you override __eq__ and the object is immutable, you should also override __hash__ in order for the class to be properly hashable. In prac

Solution 1:

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:

classMyClass(object):
    def__init__(self, a, b):
        self.a = a
        self.b = b

    def__members(self):
        return (self.a, self.b)

    def__eq__(self, other):
        iftype(other) istype(self):
            return self.__members() == other.__members()
        else:
            returnFalsedef__hash__(self):
        returnhash(self.__members())

Solution 2:

Is that the equivalent of this one-liner eq?

def__eq__(self, other):
       returntype(other) istype(self) and (self.a == other.a) and (self.b == other.b)

Solution 3:

I think you can use user defined hash function is better.

classMyClass(object):

def__init__(self, a, b):
    self.a = a
    self.b = b

def__eq__(self, other):
    iftype(other) istype(self):
        return (self.a, self.b) == (other.a, other.b)
    else:
        returnNotImplementeddef__hash__(self):
    returnhash((self.a, self.b))

Post a Comment for "Recommended Way To Implement __eq__ And __hash__"