推荐的实现__eq__和__hash__的方法 [英] Recommended way to implement __eq__ and __hash__
问题描述
Python文档提到如果您覆盖 __ eq __
并且该对象是不可变的,您还应该重写 __ 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 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?
推荐答案
回答我自己的问题。似乎执行此操作的一种方法是定义一个辅助 __ members
函数,并在定义 __ hash __
和 __ eq __
。这样,就不会重复:
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())
这篇关于推荐的实现__eq__和__hash__的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!