明明定义了is_zero方法,Python程序为何报NameError错误?
为什么我的Python类中调用
is_zero方法会触发NameError? 这个报错的核心原因是你在类的方法里直接调用is_zero,但没有通过self来引用这个类成员方法,同时你的is_zero方法本身也不符合类方法的定义规范,另外代码里还有几个小细节错误,我来一步步拆解:
问题1:is_zero方法缺少self参数
在Python的类中,实例方法必须把self作为第一个参数(用来代表实例本身),你的is_zero方法没有这个参数,Python会把传入的value当成self,导致后续调用出错,同时也无法通过实例来访问它。
问题2:调用is_zero时没有使用self
在test方法里,你直接写了is_zero(coord),但这个方法是属于ZeroList类的实例方法,必须通过self.is_zero(coord)来调用,否则Python会认为你在找全局作用域里的is_zero函数,自然会报NameError。
问题3:拼写错误
test方法里写的是self.coordinate,但你在__init__里定义的是self.coordinates(多了个s),这会导致遍历的时候找不到这个属性。
问题4:缺少math模块的导入
你使用了math.isclose,但代码开头没有导入math模块,运行时会触发另一个NameError。
修正后的完整代码
import math class ZeroList(object): def __init__(self, coordinates): self.coordinates = coordinates def is_zero(self, value): # 添加self参数 return math.isclose(value, 0) def test(self): for coord in self.coordinates: # 修正拼写错误 if not self.is_zero(coord): # 通过self调用类方法 print(coord) a = ZeroList([1,2,0,8,5,0,3,7,0,3]) a.test()
运行这段代码后,就会输出所有非零的数值:1 2 8 5 3 7 3。
内容的提问来源于stack exchange,提问作者Zach
相关产品推荐
相关产品推荐

