首页 > 解决方案 > 明确定义方法时出现 NameError

问题描述

我在 python 中有一个非常简单的程序来检查列表中是否有零值

class ZeroList(object): 
   def __init__(self,coordinates):
       self.coordinates = coordinates

   def is_zero(value):
       return math.isclose(value,0)

   def test(self):  
    for coord in self.coordinate:
        if not is_zero(coord):
            print(coord)    
a = ZeroList([1,2,0,8,5,0,3,7,0,3])
a.test()

然而运行这会导致错误

Traceback (most recent call last):
 File "line2.py", line 2, in <module>
  class Test(object):
  File "line2.py", line 12, in Test
    test([1,2,3])
   File "line2.py", line 8, in test
     if not is_zero(i):
  NameError: name 'is_zero' is not defined

方法 is_zero 已明确定义,为什么会出现此错误?

标签: python

解决方案


推荐阅读