Skip to content

Instantly share code, notes, and snippets.

@kpsychas
Last active August 3, 2016 19:39
Show Gist options
  • Save kpsychas/832be9194ed8fb26139b463c59803c36 to your computer and use it in GitHub Desktop.
Save kpsychas/832be9194ed8fb26139b463c59803c36 to your computer and use it in GitHub Desktop.
Example of overriding object equality in python
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