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

Python运行报错AttributeError: 'str' object has no attribute 'describe'求解

错误产生原因

你当前代码触发报错的直接原因是:你创建的Computer_1根本不是Computer类的实例,只是被括号包裹的字符串对象,字符串本身没有describe方法,因此抛出属性不存在的错误。
除此之外你的代码还有3处隐含错误:

  • 类构造方法的定义错误:Python的构造方法要求是左右各2个下划线、拼写为init,你写的_inti_不仅下划线数量不对,拼写也错误,就算正确创建实例也无法正常初始化属性
  • 实例创建语法错误:创建类实例需要调用类名+括号传参,你直接把字符串赋值给变量,完全没有关联到你写的Computer类
  • 类属性no_of_Computer的定义位置错误:你写在了构造方法内部作为局部变量,无法实现全局计数的效果,需要放到类下第一层作为类属性
  • 传参格式错误:你把storage、color、system三个参数塞到了同一个字符串里,就算正确调用类也无法正常拆分三个属性
修复后的完整代码
class Computer:
    # 类属性放在构造方法外
    no_of_Computer = 0
    # 构造方法使用双下划线,拼写修正为init
    def __init__(self, storage, color, system):
        self.storage = storage
        self.color = color
        self.system = system
        Computer.no_of_Computer +=1

    def describe(self):
        print(f'my storage is {self.storage} and my color is {self.color} and my system is {self.system}')

# 正确创建类实例:调用类名,拆分3个参数分别传入
Computer_1 = Computer("1TB", "silver", "windows")
Computer_2 = Computer("4TB", "black", "linux")
Computer_3 = Computer("9TB", "white", "mac")

Computer_1.describe()
运行输出结果
my storage is 1TB and my color is silver and my system is windows

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:36:03