我的目标是得到两个包含对象的列表之间的差异。你知道吗
我实现了一个名为Branch的类,并覆盖了它的__eq__
和__ne__
方法,如下所示:
class Branch(object):
def __str__(self):
return self.name
def __eq__(self, other):
if isinstance(other, Branch):
return (self.valueFrom == other.valueFrom) \
and (self.valueTo == other.valueTo) \
and (self.inService == other.inService)
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return result
return not result
def __init__(self, name, valueFrom, valueTo, inService=True):
self.name = name
self.valueFrom = valueFrom
self.valueTo = valueTo
self.inService = inService
我的第一次尝试是使用来自set
类型的方法difference
。然而,这似乎是不可能的,因为它使用的是对象的散列,而不是我想要的__eq__
方法。你知道吗
以下代码显示了问题:
b1 = Branch("branch1", 1, 2)
b1b = Branch("equal to branch1", 1, 2)
b2 = Branch("branch2", 2, 3)
b3 = Branch("branch3", 3, 1)
b3_off = Branch("branch3 not in service", 3, 1, False)
l1 =[b1,b2,b3]
l2 =[b1b,b2,b3_off]
difference = set(l1).difference(l2)
for branch in difference:
print branch
输出为:
>>>
branch1
branch3
但是,我希望只将branch3作为输出,因为b1
和b1b
应该被视为相等的。你知道吗
是否可以使用集合来解决此问题?或者我应该从不同的角度来处理这个问题?你知道吗
您需要实现散列,您选择什么取决于您自己,但以下几点可行:
您只需要实现hash和eq:
相关问题 更多 >
编程相关推荐