You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类调用报错:'str'对象无'sequence'属性,求原因分析

错误原因分析与修复方案

核心错误原因

你触发AttributeError的根本问题是调用实例方法的方式错误:

  • seq_length是类的实例方法,这类方法必须通过类的实例对象调用,而非直接用类本身调用。
  • 当你写ProtSeq.seq_length(AAcodes)时,Python会把传入的字符串AAcodes当作实例方法的第一个参数self。而字符串对象没有sequence属性,自然会报错。

正确的使用步骤

要使用这个类,必须先完成实例初始化,再调用实例方法:

  1. 用ProtSeq()创建实例,传入sequence、identifier等必要参数;
  2. 通过创建好的实例调用seq_length()方法。

代码里的其他冗余问题

  • __init__方法中的length参数完全多余,序列长度可直接通过len(self.sequence)计算,无需提前传入;
  • seq方法里的sequence = AAcodes是定义局部变量,和实例的self.sequence无关,若要返回实例存储的序列,应改为return self.sequence。

修复后的完整代码

class ProtSeq():
    '''A class that holds a protein sequence'''

    def __init__(self, sequence, identifier, function=''):
        '''Initialise the class'''
        self.identifier = identifier
        self.sequence = sequence
        self.function = function # optional functional description
    
    def get_seq(self):
        # 返回实例存储的蛋白质序列
        return self.sequence
    
    def seq_length(self):
        length = len(self.sequence)
        print('Length of {} is {} amino acids. '.format(self.sequence, length))

AAcodes = 'ACDEFGHIKLMNPQRSTVWY'
# 1. 创建类的实例
prot_instance = ProtSeq(sequence=AAcodes, identifier='standard_aa')
# 2. 通过实例调用方法
prot_instance.seq_length()

内容的提问来源于stack exchange,提问作者zestycodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:25:04