0

我有一本字典,其中 ID 作为键,类作为条目。当我尝试附加到一个特定类的变量时,字典中的所有其他类也被附加到。

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。我错过了一些明显的东西吗?

4

1 回答 1

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

这就是为什么你从不使用可变对象作为参数默认值的原因(好吧,除非你有充分的理由)。

于 2013-02-07T14:20:53.200 回答