Recommended way to implement __eq__ and __hash__

倖福魔咒の 提交于 2019-12-10 04:06:50

问题


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 practice, when I do this I often end up with code like

class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __eq__(self, other):
        if type(other) is type(self):
            return (self.a == other.a) and (self.b == other.b)
        else:
            return False

    def __hash__(self):
        return hash((self.a, self.b))

This is somewhat repetitive, and there is a clear risk of forgetting to update one when the other is updated.

Is there a recommended way of implementing these methods together?


回答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:

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())


来源:https://stackoverflow.com/questions/45164691/recommended-way-to-implement-eq-and-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!