2016-02-01 66 views
2

我有在python比較兩個自定義列表蟒蛇

我轉換消息比較對象的兩個列表麻煩到

class StatusMessage(object): 
    def __init__(self, conversation_id, platform): 
     self.__conversation_id = str(conversation_id) 
     self.__platform = str(platform) 

    @property 
    def conversation_id(self): 
     return self.__conversation_id 

    @property 
    def platform(self): 
     return self.__platform 

現在,當我創建類型StatusMessage的兩個列表

>>> expected = [] 
>>> expected.append(StatusMessage(1, "abc")) 
>>> expected.append(StatusMessage(2, "bbc")) 

>>> actual = [] 
>>> actual.append(StatusMessage(1, "abc")) 
>>> actual.append(StatusMessage(2, "bbc")) 

,然後我比較使用

>>> cmp(actual, expected) 
兩個列表

>>> len(set(expected_messages_list).difference(actual_list)) == 0 

我不斷收到故障。 當我調試,實際上在列表中像

>>> actual[0].conversation_id == expected[0].conversation_id 
>>> actual[0].platform == expected[0].platform 

比較每個項目,然後我總是看到

True 

做如下返回-1

>>> cmp(actual[0], expected[0]) 

爲什麼會這樣。我錯過了什麼?

回答

2

你必須告訴蟒蛇如何檢查StatusMessage類的兩個實例是否相等。

例如,添加方法

def __eq__(self,other): 
    return (self is other) or (self.conversation_id, self.platform) == (other.conversation_id, other.platform) 

將具有以下效果:

>>> cmp(expected,actual) 
0 
>>> expected == actual 
True 

如果你想使用cmpStatusMessage對象,考慮實施__lt____gt__方法以及。我不知道哪個規則要考慮一個實例小於或大於另一個實例。

此外,考慮了StatusMessage對象與沒有conversation_idplatform屬性中的任意對象比較返回False或錯誤檢查。否則,你會得到一個AttributeError

>>> actual[0] == 1 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "a.py", line 16, in __eq__ 
    return (self is other) or (self.conversation_id, self.platform) == (other.conversation_id, other.platform) 
AttributeError: 'int' object has no attribute 'conversation_id' 

你可以找到一個原因self is other檢查是一個好主意here(在多線程應用中可能出現意外結果)。

+0

謝謝你的答案timgeb。但是,這是事情,當我比較列表中的元素的順序應該很重要。這就是爲什麼我的第一個方法是使用設置和區別 –

+0

嗯,我試着整理列表,然後做了比較,它爲我工作。 –

0

因爲您正在嘗試比較兩個自定義對象,所以您必須定義是什麼使對象相等或不相等。您可以通過定義在StatusMessage__eq__()方法做到這一點:

class StatusMessage(object): 
    def __eq__(self, other): 
     return self.conversation_id == other.conversation_id and 
       self.platform == other.platform