How To Define __hash__ When An Object Can Be Equal To Different Kind Of Objects?
In Python doscumentation, we can read about __hash__ function : The only required property is that objects which compare equal have the same hash value. I have an object which
Solution 1:
You can't define a consistent hash. First, your class does not define __eq__
consistently; it is not guaranteed that if x == y
and y == z
, then x == z
. Second, your object is mutable. In Python, mutable objects are not supposed to be hashable.
If a class defines mutable objects and implements a
__cmp__()
or__eq__()
method, it should not implement__hash__()
, since hashable collection implementations require that a object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).
Example of broken ==
:
x = MyClass('foo')
y = 'foo'z = MyClass('foo')
x == y # Truey == z # Truex == z # False
Post a Comment for "How To Define __hash__ When An Object Can Be Equal To Different Kind Of Objects?"