比较具有嵌套列表作为属性的两个对象

Comparison of two objects with nested lists as properties

我有一个 class 看起来像这样:

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 是不够的。

修复您的 __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

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