两个对象的比较,属性为嵌套列表

2024-04-25 08:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一节课看起来是这样的:

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”可能是一个foo列表,其中“c”包含foo列表,例如:

[Foo(1,2), Foo(3,4,[Foo(5,6)])] 

在给定列表结构/对象结构的情况下,处理这种类型的对象比较的好方法是什么?我假设仅仅做self.c == other.c是不够的。你知道吗


Tags: 对象selfnone列表objectfooinitis
2条回答

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

相关问题 更多 >