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
相关产品推荐
相关产品推荐

