Search code examples
pythonobjectobject-comparison

Comparison of two objects with nested lists as properties


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.


Solution

  • 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