2014-05-05 55 views
0

我有一個擴展列表對象的類,看起來合適,因爲它是的列表,該類也有兩個布爾屬性用於過濾返回值。如何過濾擴展列表對象的類的返回值

我能夠填充調用self.append的類,該類用於接收列表字典並附加存儲該字典內容的類的實例;該類存儲特定類的實例列表,很像其他語言的向量。

下面是一個示例代碼:

data = [ 
    { 'id': 0, 'attr1': True, 'attr2': False }, 
    { 'id': 1, 'attr1': False, 'attr2': True }, 
    { 'id': 2, 'attr1': False, 'attr2': False }, 
    { 'id': 3, 'attr1': True, 'attr2': True } 
] 

class MyClass(object): 
    def __init__(self, data): 
     self.id = data['id'] 
     self.attr1 = data['attr1'] 
     self.attr2 = data['attr2'] 

class MyList(list): 
    condition1 = True 
    condition2 = True 

    def __init__(self, data): 
     for content in data: 
      self.append(MyClass(content)) 

這實際工作,這意味着我得到一個列表ØMyClasses情況下,現在是我想要做的是,如果我條件1的值更改爲false,當我訪問它應該如此篩選結果的列表:

my_list = MyList(data) 
for item in my_list: 
    print 'id', item.id, 'attr1', item.attr1, 'attr2', item.attr2 
# >> id 0 attr1 True attr2 False 
# >> id 1 attr1 False attr2 True 
# >> id 2 attr1 False attr2 False 
# >> id 3 attr1 True attr2 True 

my_list.condition1 = False 
# Now it should list only the instances of MyClass that has the attr1 set to False 
for item in my_list: 
    print 'id', item.id, 'attr1', item.attr1, 'attr2', item.attr2 
# >> id 1 attr1 False attr2 True 
# >> id 2 attr1 False attr2 False 

我對Python很新,所以我不確定即使我可以做到這一點。

+0

什麼是MyClass中的ID的目的是什麼?順便說一句,它不工作。 – Daniel

+0

好的,我只是編輯了代碼,所以它更簡潔。 爲了回答你的問題,本例中MyClass中的id純粹是美學的,所以從迭代中讀取輸出更容易。 –

+1

類不像其他語言那樣頻繁使用。你的問題在python中是單行的:''for filter in item(lambda n:n ['attr1'] is False,data):print'id',item ['id'],'...' – Daniel

回答

0

你需要重寫__iter__,例如:

class MyList(list): 

    def __init__(self, data): 
     self.condition1 = True 
     self.condition2 = True 
     for content in data: 
      self.append(MyClass(content)) 

    def __iter__(self): 
     return (self[i] for i in range(len(self)) 
       if ((self.condition1 or self[i].attr1) and 
        (self.condition2 or self[i].attr2))) 

請注意,我已經例如由condition1一個實例,不是class,屬性;我假設你可以爲這些標誌設置不同的實例。

此外,您必須在MyClass上實施__eq__才能將其用於例如my_class in my_list,並且可以簡化MyClass.__init__到:

def __init__(self, data): 
    self.__dict__.update(data) 
+0

感謝@jonrsharpe,工作,並感謝有關實例屬性和__dict __。更新的提示。 ;) –