Created
February 29, 2016 05:13
-
-
Save alexcpn/0e604c8ddcc56debda40 to your computer and use it in GitHub Desktop.
Python Proper way to override equal to and hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes | |
# http://stackoverflow.com/questions/4352244/python-implementing-ne-operator-based-on-eq/30676267#30676267 | |
class Test1(object): | |
""" | |
Proper way to override equality | |
""" | |
def __init__(self, str1, str2, num1): | |
self.str1 = str1 | |
self.str2 = str2 | |
self.num1 = num1 | |
def __eq__(self, other): | |
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ | |
# If you dont define ne when overriding eq you get inconsisten behaviour | |
def __ne__(self, other): | |
return not self == other | |
def __hash__(self): | |
data = [ | |
self.str1, | |
self.num1, | |
self.__class__ | |
] | |
return hash("{},{},{}".format(*sorted(data))) | |
k1 = Test1("1","11",1) | |
k2 = Test1("1","11",1) | |
print k1 == k2 # True | |
print k1 != k2 # False but will evaluvate to True if you comment out override the ne part!! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment