我很难理解如何根据每个实例拥有的底层字典属性正确比较对象。
由于我正在覆盖__eq__
,所以我需要同时覆盖__hash__
吗?我对何时/在何处这样做没有明确的了解,真的需要一些帮助。
我创建了一个简单的示例来说明我遇到的最大递归异常。 RegionalCustomerCollection
按地理区域组织帐户ID。RegionalCustomerCollection
对象如果它们的区域及其相应的accountid
是相等的,则被认为是相等的。基本上,所有的items()
内容应该是相等的。
from collections import defaultdict
class RegionalCustomerCollection(object):
def __init__(self):
self.region_accountids = defaultdict(set)
def get_region_accountid(self, region_name=None):
return self.region_accountids.get(region_name, None)
def set_region_accountid(self, region_name, accountid):
self.region_accountids[region_name].add(accountid)
def __eq__(self, other):
if (other == self):
return True
if isinstance(other, RegionalCustomerCollection):
return self.region_accountids == other.region_accountids
return False
def __repr__(self):
return ', '.join(["{0}: {1}".format(region, acctids)
for region, acctids
in self.region_accountids.items()])
让我们创建两个对象实例,并填充一些示例数据:
>>> a = RegionalCustomerCollection()
>>> b = RegionalCustomerCollection()
>>> a.set_region_accountid('northeast',1)
>>> a.set_region_accountid('northeast',2)
>>> a.set_region_accountid('northeast',3)
>>> a.set_region_accountid('southwest',4)
>>> a.set_region_accountid('southwest',5)
>>> b.set_region_accountid('northeast',1)
>>> b.set_region_accountid('northeast',2)
>>> b.set_region_accountid('northeast',3)
>>> b.set_region_accountid('southwest',4)
>>> b.set_region_accountid('southwest',5)
现在让我们尝试比较这两个实例并生成递归异常:
>>> a == b
...
RuntimeError: maximum recursion depth exceeded while calling a Python object
__eq__
和__hash__
方法。除非您需要进行比较(例如hash(self) == hash(other)
),否则您并不一定需要实现__hash__
方法。 - jonrsharpe