首页 > 解决方案 > 为什么在 Python 类中定义本地函数时出现“对象没有属性”错误?

问题描述

我正在写一个类,其中有一个带有本地参数的方法。

class GlobalAssign:
    def __init__(self, seq1, seq2, d=-5, mismatch=-5, trans=-7):
        self.seq1 = list(seq1)
        self.seq2 = list(seq2)
        self.mismatch = mismatch
        self.d = d
        self.trans = trans
    def score(self, a, b):
        # score for any pair of bases
        pair = (str(a).capitalize(), str(b).capitalize())
        if pair in {('A', 'G'), ('G', 'A'), ('C', 'T'), ('T', 'C')}:
            return self.mismatch
        if pair in {('A', 'C'), ('C', 'A'), ('T', 'G'), ('G', 'T'),
                    ('A', 'T'), ('T', 'A'), ('C', 'G'), ('G', 'C')}:
            return self.trans
        elif a == '-' or b == '-':
            return self.d

我在终端中运行以下代码:

In [62]: test = GlobalAssign('agcg','gtat')

In [63]: test.score('a','g')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-63-f387aa9ccad8> in <module>
----> 1 test.score('a','g')

~/data/needleman.py in score(self, a, b)
     11     def score(self, a, b):
     12         # score for any pair of bases
---> 13         pair = (str(a).capitalize(), str(b).capitalize())
     14         if pair in {('A', 'G'), ('G', 'A'), ('C', 'T'), ('T', 'C')}:
     15             return self.mismatch

AttributeError: 'GlobalAssign' object has no attribute 'a'

我认为ab是局部变量,所以我不需要写 self.a。但它引发了这个错误,我有点困惑。已经卡了一段时间。谢谢你能帮我弄清楚。

标签: pythonclass

解决方案


我刚刚在本地运行您的代码并且它正在运行;它给了我-5的输出。

为了获得所有案例,我对您的代码进行了一些调整:

class GlobalAssign:
    def __init__(self, seq1, seq2, d=-5, mismatch=-5, trans=-7):
        self.seq1 = list(seq1)
        self.seq2 = list(seq2)
        self.mismatch = mismatch
        self.d = d
        self.trans = trans
    def score(self, a, b):
        # score for any pair of bases
        pair = (str(a).capitalize(), str(b).capitalize())
        if pair in [('A', 'G'), ('G', 'A'), ('C', 'T'), ('T', 'C')]:
            return self.mismatch
        elif pair in [('A', 'C'), ('C', 'A'), ('T', 'G'), ('G', 'T'),
                    ('A', 'T'), ('T', 'A'), ('C', 'G'), ('G', 'C')]:
            return self.trans
        elif a == '-' or b == '-':
            return self.d
        else:
            print("Value not correct.")
            return None

此外,我已卸下支架{}并替换[]为方法内部score

让我知道这是否对您有帮助。


推荐阅读