collections.Counter 包含的相关方法

Relevant method to include for collections.Counter

如果这是网站上的重复,我们深表歉意(我四处搜索但找不到答案)。假设我在 Python 中实现了 Person class,其中包含名称和年龄参数,例如 Person('Bob', 25)。假设我创建了一个 Person 对象列表,我想知道每个实例有多少;例如,我可能有 [Person('Bob', 25), Person('Sally', 40'), Person('Bob', 25), Person('Sarah', 30)]。所以 Person('Bob', 25) 有两个实例,其余的有 1 个实例;如果要 运行 collections.Counter 在此对象列表上,它将 return 正确。

我的问题是:collections.Counter 究竟在数据结构中寻找什么以使计数正确?我有一个更复杂(但可散列)的 class,并且 collections.Counter 没有正确计算元素的数量。我确定这是因为我只是在定义中缺少一些方法,但我不确定它是什么。

如果a == b那么hash(a) == hash(b)

您需要实施__hash__() and __eq__()