Reputation: 143
Apologies if this is a repeat on the site (I searched around but couldn't find an answer). Say I have a Person
class implemented in Python with name and age parameters, like Person('Bob', 25)
. Say I then create a list of Person
objects and I want to know how many of each instance there are; for example, I might have [Person('Bob', 25), Person('Sally', 40'), Person('Bob', 25), Person('Sarah', 30)]
. So there are two instances of Person('Bob', 25)
and 1 instance for the remainder; if were to run collections.Counter on this list of objects, it would return this correctly.
My question is: what exactly does collections.Counter look for in a data structure such that the count is correct? I have a more complicated (but hashable) class, and collections.Counter isn't counting the number of elements correctly. I'm sure this is because I just have some method missing from the definition, but I'm not sure what it is.
Upvotes: 0
Views: 40
Reputation: 76
If a == b
then hash(a) == hash(b)
You need to implement __
hash__
() and __
eq__
()
Upvotes: 1