我有一个看起来像这样的课程:
class Foo(object):
def __init__(self, a, b, c=None):
self.a = a
self.b = b
self.c = c # c is presumed to be a list
def __eq__(self, other):
return self.a == other.a and self.b == other.b
然而,在这种情况下" c"可能是一个Foos列表,其中" c" s包含Foos列表,例如:
[Foo(1,2), Foo(3,4,[Foo(5,6)])]
在给定列表结构/对象结构的情况下,处理这种类型的对象比较有什么好方法?我假设只是做一个self.c == other.c
就不够了。
答案 0 :(得分:0)
修复__eq__
方法
class Foo(object):
def __init__(self, a, b, c=None):
self.a = a
self.b = b
self.c = c # c is presumed to be a list
def __eq__(self, other):
return self.a == other.a \
and self.b == other.b and self.c == other.c
a,b = Foo(2,3), Foo(5,6)
c = Foo(1,2, [a,b])
d = Foo(1,2)
e,f = Foo(2,3), Foo(5,6)
g = Foo(1,2, [e,f])
print c == d #False
print c == g #True
答案 1 :(得分:-2)
Foo中n
属性的通用解决方案:
class Foo(object):
def __init__(self, a, b, c=None):
self.a = a
self.b = b
self.c = c # c is presumed to be a list
def __eq__(self, other):
for attr, value in self.__dict__.iteritems():
if not value == getattr(other, attr):
return False
return True
item1 = Foo(1, 2)
item2 = Foo(3, 4, [Foo(5, 6)])
item3 = Foo(3, 4, [Foo(5, 6)])
print(item1 == item2) # False
print(item3 == item2) # True