2016-02-26 47 views
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」可能是FOOS的列表,包含個「C」 FOOS,前類似的列表:

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

什麼是在處理這種類型的對象比較的好方法,給出的列表結構/對象結構?我假設簡單地做一個self.c == other.c是不夠的。

+1

爲什麼你認爲這是一個問題嗎?如果您比較列表,Python會比較它們中的元素以確定它們是否相等(假設它們的長度相同,首先檢查它)。見例如http://stackoverflow.com/q/29215418/3001761 – jonrsharpe

+0

解決您的'__eq__'使用'=='而不是'='並且包括'c'的比較。 –

+0

'return(allat)(getattr(self,n)== getattr(other,n)for n'('a','b','c'))' – Kupiakos

回答

0

修理你__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 
-2

一個通用的解決方案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 
+0

您還可以添加類型檢查以避免誤報。 '如果不是自我.__ class__ == other .__ class__:return False' –

+0

不是我,對不起。 –