初学Python OOP调用同类方法报NameError问题求解
问题分析
- 类内的实例方法调用必须通过
self前缀访问,直接写函数名解释器会尝试查找全局作用域的同名函数,找不到就会抛出NameError,这是你报错的核心原因。 - 实例方法的
self参数会在调用时自动传入,不需要手动传递类属性作为参数,你定义的standup方法仅需self一个参数,调用时不需要额外传self.issitting。 - 额外注意:你贴出的代码里类下方的所有方法都没有正确缩进,Python 中类的成员必须缩进4个空格才会被识别为类的一部分,否则会被判定为全局函数,也会导致调用失败。
修正方案
把move_teddy方法中调用standup的行修改为:
self.situation = self.standup()
同时确保所有类内方法都缩进在class StuffAnimal:代码块内。
修正后完整参考代码
class StuffAnimal: def __init__(self,name,color,weight,issitting): self.name = name self.color = color self.weight = weight self.issitting = issitting self.x = 0 self.y = 0 self.situation = " " def standup(self): if self.issitting == True : print("the stuff toy is sitting") return "sit" else : print ("the stuff toy is not sitting") return "notsit" def move_teddy(self): # 修正方法调用逻辑 self.situation = self.standup() if self.situation == 'sit' : # 原逻辑提示写反,坐着时需要把issitting改为False才能移动 print ("teddy is not in the situation to move please change issitting to False") elif self.situation == 'notsit' : print ("teddy is in the situation to move please give cordinates") self.x = int(input("x cordinates : ")) self.y = int(input("y cordinates : ")) print("teddy moved to ",self.x,self.y)
调用测试
# 实例化后正常调用 teddy = StuffAnimal("泰迪", "棕色", 2, False) teddy.move_teddy()
内容的提问来源于stack exchange,提问作者aditya pakala
相关产品推荐
相关产品推荐

