Recommended way to implement __eq__ and __hash__

后端 未结 2 547
灰色年华
灰色年华 2021-02-13 11:30

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

相关标签:
2条回答
  • 2021-02-13 11:53

    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())
    
    0 讨论(0)
  • 2021-02-13 11:58

    Is that the equivalent of this one-liner eq?

       def __eq__(self, other):
           return type(other) is type(self) and (self.a == other.a) and (self.b == other.b)
    
    0 讨论(0)
提交回复
热议问题