Last active
August 3, 2016 19:39
-
-
Save kpsychas/832be9194ed8fb26139b463c59803c36 to your computer and use it in GitHub Desktop.
Example of overriding object equality in python
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
from collections import Counter | |
class A(object): | |
def __init__(self, name, val): | |
self.name = name | |
self.val = val | |
def __repr__(self): | |
return 'A(val={})'.format(self.val) | |
def __eq__(self, other): | |
return self.val == other.val | |
def __hash__(self): | |
return hash(self.__repr__()) | |
def main(): | |
x = A('one', 1) | |
y = A('uno', 1) | |
z = A('two', 2) | |
w = A('dos', 2) | |
print(x == y) # True | |
print(x == z) # False | |
# only one of x,y and z,w will remain in sets so name | |
# information will be lost in both containers | |
print(set([x, y, z, w])) # set([A(val=1), A(val=2)]) | |
print(Counter([x, y, z, w])) # Counter({A(val=1): 2, A(val=2): 2}) | |
x.name = '1' # This is acceptable | |
x.val = 3 # This *must not* happen! | |
# Behavior of previous objects is undefined after this update | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment