Skip to content

Instantly share code, notes, and snippets.

@RoelandMatthijssens
Last active October 6, 2016 12:47
Show Gist options
  • Save RoelandMatthijssens/e29d10e9325edb920d7ae676a3e855d4 to your computer and use it in GitHub Desktop.
Save RoelandMatthijssens/e29d10e9325edb920d7ae676a3e855d4 to your computer and use it in GitHub Desktop.
from collections import Counter
class Score():
def __init__(self, name, points):
self.name = name
self.points = points
def __hash__(self):
return hash(tuple([self.name, self.points]))
def __eq__(self, other):
return self.name == other.name and self.points == other.points
def __ne__(self, other):
return self.name != other.name or self.points != other.points
x = Counter([
Score('John', 1),
Score('Jeff', 2),
Score('Bob', 3),
Score('Dave', 4),
])
y = Counter([
Score('John', 1),
Score('Bob', 3),
Score('Jeff', 2),
Score('Dave', 4),
])
assert x == y
@pieterdd
Copy link

pieterdd commented Oct 6, 2016

Tip for your __eq__ implementation: you can use return self.__dict__ == other.__dict__ as http://stackoverflow.com/questions/1227121/compare-object-instances-for-equality-by-their-attributes-in-python suggests. Also: do you need to override __ne__ if you implement __eq__?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment