2013-02-07 355 views
0

我有一個字典ID爲鍵和類作爲條目。當我嘗試附加到某個特定類的變量時,字典中的所有其他類也會附加到該類。Python字典的追加值分配給所有字典條目

class Reaction: 
    def __init__(self, bkm_id, ec_nums = [], b_ids = [], k_ids = [], m_ids = [], source = ''): 
     self.bkm_id = bkm_id 
     self.ec_nums = ec_nums 
     self.b_ids = b_ids 
     self.k_ids = k_ids 
     self.m_ids = m_ids 
     self.source = source 

     self.substrates = [] 
     self.products = [] 

    def add_metabolite(self, metabolite, stoichiometry, subs_prod): 
     if subs_prod == 'S': 
      self.substrates.append(Substrate_Product(metabolite, stoichiometry)) 
     elif subs_prod == 'P': 
      self.products.append(Substrate_Product(metabolite, stoichiometry)) 

定義了類。然後,如果我輸入:

rxna = Reaction('a') 

rxnb = Reaction('b') 

dict = {} 

dict['a'] = rxna 

dict['b'] = rxnb 

dict 
Out[14]: 
{'a': <__main__.Reaction instance at 0x102c51fc8>, 
'b': <__main__.Reaction instance at 0x102c62518>} 

dict['a'].b_ids.append('BID') 

dict['a'].b_ids 
Out[16]: ['BID'] 

dict['b'].b_ids 
Out[17]: ['BID'] 

rxnb.b_ids 
Out[18]: ['BID'] 

,而我只是想追加「BID」到rxna.b_ids。我錯過了明顯的東西嗎?

回答

2

這些列表在類定義中創建一次,因此被所有實例共享。你想:

class Reaction: 
    def __init__(self, bkm_id, ec_nums=None, b_ids=None, k_ids=None, m_ids=None, source = '') 
     self.bkm_id = bkm_id 
     self.ec_nums = ec_nums 
     self.b_ids = b_ids or [] 
     self.k_ids = k_ids or [] 
     self.m_ids = m_ids or [] 
     self.source = source 

     self.substrates = [] 
     self.products = [] 

    def add_metabolite(self, metabolite, stoichiometry, subs_prod): 
     if subs_prod == 'S': 
      self.substrates.append(Substrate_Product(metabolite, stoichiometry)) 
     elif subs_prod == 'P': 
      self.products.append(Substrate_Product(metabolite, stoichiometry)) 

這就是爲什麼你從來沒有使用可變對象作爲參數的默認值(當然,除非你有一個很好的理由)。

+0

謝謝,作品像一個夢(一個美好的夢)! –

+1

如果它適合您,請將此答案標記爲「已接受」。 –