Comparison of two objects with nested lists as properties

858 Views Asked by At

I have a class that looks like so:

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

However, in this case "c" might be a list of Foos, with "c"s that contains list of Foos, ex something like:

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

What is a good approach in dealing with this type of object comparison, given the list structure / object structure? I'm assuming that simply doing a self.c == other.c is insufficient for this.

2

There are 2 best solutions below

0
On BEST ANSWER

Fixing your __eq__ method

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
On

A generic solution to n attributes in Foo:

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