Monday, 9 September 2013

Make Counter consider two objects of the same class the same

Make Counter consider two objects of the same class the same

I'm using collections.Counter. It's great so far, except that I'd like it
to count objects of the same class as the same. How can I do this? I tried
overriding the hash() method on the class so that all instances would hash
the same. Right now, if I do Counter([Type1(), Type1(), Type2(), Type2()])
it will return {<Type1 object at...>:1,<Type1 object at...>:1,<Type2
object at...>:1,<Type2 object at...>:1} I would prefer it to return
something like {"Type1":2, "Type2":2} instead. Is this possible? I was
poking around the docs and couldn't figure out how to make it work.
I should add that the classes I'm using are essentially wrappers for
constant values. It's just more convenient to wrap them in a class. Under
no circumstances will one Type1 object ever differ from another Type1
object.

No comments:

Post a Comment