0

私は次のようなクラスを持っています:

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)])] 

リスト構造/オブジェクト構造を考えると、このタイプのオブジェクト比較に対処するための良いアプローチは何ですか? これには単に a を実行するだけでself.c == other.cは不十分だと思います。

4

2 に答える 2

-2

nFoo の属性に対する一般的な解決策:

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
于 2016-02-26T22:16:56.273 に答える