Python: Class 变量未更新

Python: Class variables are not updated

大家好,

我无法弄清楚这里的问题,因此想听听您的意见。

这是我的代码:

from collections import defaultdict

class peptide():

    aa_lib={
        'A':   {'H': 5, 'C': 3, 'O': 1, 'N': 1},
        'C':   {'H': 5, 'C': 3, 'S': 1, 'O': 1, 'N': 1},
        'D':   {'H': 5, 'C': 4, 'O': 3, 'N': 1},
        'E':   {'H': 7, 'C': 5, 'O': 3, 'N': 1},
        'F':   {'H': 9, 'C': 9, 'O': 1, 'N': 1},
        'G':   {'H': 3, 'C': 2, 'O': 1, 'N': 1},
        'H':   {'H': 7, 'C': 6, 'N': 3, 'O': 1},
        'I':   {'H': 11, 'C': 6, 'O': 1, 'N': 1},
        'K':   {'H': 12, 'C': 6, 'N': 2, 'O': 1},
        'L':   {'H': 11, 'C': 6, 'O': 1, 'N': 1},
        'M':   {'H': 9, 'C': 5, 'S': 1, 'O': 1, 'N': 1},
        'N':   {'H': 6, 'C': 4, 'O': 2, 'N': 2},
        'P':   {'H': 7, 'C': 5, 'O': 1, 'N': 1},
        'Q':   {'H': 8, 'C': 5, 'O': 2, 'N': 2},
        'R':   {'H': 12, 'C': 6, 'N': 4, 'O': 1},
        'S':   {'H': 5, 'C': 3, 'O': 2, 'N': 1},
        'T':   {'H': 7, 'C': 4, 'O': 2, 'N': 1},
        'V':   {'H': 9, 'C': 5, 'O': 1, 'N': 1},
        'W':   {'C': 11, 'H': 10, 'N': 2, 'O': 1},
        'Y':   {'H': 9, 'C': 9, 'O': 2, 'N': 1},
        'H-':  {'H': 1},
        '-OH': {'O': 1, 'H': 1}
    }

    def __init__(self,sequence,rtime,intensity,protein):
        self.sequence=sequence
        self.carbon_atoms=0
        self.nitrogen_atoms=0
        self.hydrogen_atoms=0
        self.sulfur_atoms=0
        self.oxygen_atoms=0

        self.rt=rtime
        self.intensity=intensity
        self.protein=protein
        #self.charge=charge

    def sumForm(self, aa_lib):
        atom_comp = defaultdict(int)
        for aa in self.sequence:
            if aa in aa_lib.keys():
                for atom, count in aa_lib[aa].items():
                    atom_comp[atom]+=count
        self.carbon_atoms=atom_comp['C']
        self.nitrogen_atoms=atom_comp['N']
        self.hydrogen_atoms=atom_comp['H']
        self.sulfur_atoms=atom_comp['S']
        self.oxygen_atoms=atom_comp['O']

test=peptide("FKDDLA", 2.5, 2E+7, "OmpF")
test.sumForm

我不明白为什么原子没有更新。初始值 (0) 仍然保留,而不是更新后的值。在 class 之外我可以让它工作。

你有两个问题:

  1. 您永远不会调用该方法,您需要 test.sumForm()
  2. 你的方法接受了一个你没有传入的参数。

您可以执行 test.sumForm(peptide.aa_lib),也可以修改您的方法以直接从 class 读取变量,如下所示:

def sumForm(self):  # note, no more aa_lib here
    atom_comp = defaultdict(int)
    for aa in self.sequence:
        if aa in peptide.aa_lib.keys(): # peptide.aa_lib
            for atom, count in peptide.aa_lib[aa].items():
                atom_comp[atom]+=count
    self.carbon_atoms=atom_comp['C']
    self.nitrogen_atoms=atom_comp['N']
    self.hydrogen_atoms=atom_comp['H']
    self.sulfur_atoms=atom_comp['S']
    self.oxygen_atoms=atom_comp['O']

要么修改调用,要么修改方法。不要两者都做(否则你会遇到一组全新的错误)。