An easy, correct way to implement __hash__()
is to use a key tuple. It won't be as fast as a specialized hash, but if you need that then you should probably implement the type in C.
Here's an example of using a key for hash and equality:
class A:
def __key(self):
return (self.attr_a, self.attr_b, self.attr_c)
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
if isinstance(other, A):
return self.__key() == other.__key()
return NotImplemented
Also, the documentation of __hash__
has more information, that may be valuable in some particular circumstances.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…