python - 为什么在 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'
我认为a和b是局部变量,所以我不需要写 self.a。但它引发了这个错误,我有点困惑。已经卡了一段时间。谢谢你能帮我弄清楚。
解决方案
我刚刚在本地运行您的代码并且它正在运行;它给了我-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
。
让我知道这是否对您有帮助。
推荐阅读
- android - 以编程方式更改列表中每个项目的可绘制颜色
- reactjs - 如果用户是“特权”,则限制对路由的访问
- firebase - 如何在flutter中将数据从CSV文件导入数据库
- java - 使用 Gson 添加 Json 记录
- javascript - 尽管在 React js 中使用了 memo 和 useCallback,如何防止在更改父组件中的状态时不必要地重新渲染子组件
- cplex - Cplex OPL:在预处理中消除一些 dvar
- java - 在 Java 中识别无声的 wav 文件
- firebase - Flutter:在构建期间调用 setState() 或 markNeedsBuild()
- python - Scrapy crawl 命令无法正确抓取
- flutter - 颤振升级开始但在某些时候失败