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

Python类对象报错:'Robot'无'introduce_self'属性的问题求助

问题原因

你定义的introduce_self是一个独立的普通函数,没有被包含在Robot类的内部,所以Robot的实例(比如r2)并不具备这个方法,调用时就会触发AttributeError。

解决方法

将introduce_self函数缩进,放到Robot类的内部,和__init__方法保持同级缩进,让它成为类的实例方法。

修正后的代码如下:

class Robot:
    def __init__(self, rname, rcolor, rweight):
        self.name = rname
        self.color = rcolor
        self.weight = rweight

    def introduce_self(self):
        print("my name is " + self.name)


r1 = Robot("Tom", "Red", 30)
r2 = Robot("Jerry", "Blue", 40)

r2.introduce_self()

运行这段代码后,就能得到预期输出:my name is Jerry。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:15:27