未定义名称错误全局名称

时间:2013-12-26 22:31:34

标签: python

我收到了一个N​​ameError:未定义全局名称'mapping'。我哪里错了?

 class CheckFunction:
     mapping = [6,2,5,5,4,5,6,3,7,6]
     def newFunction(self,code):
        splitting = code.split()
        count = 0
        for n in splitting:
           count += mapping[int(n)]
        return count

 obj = CheckFunction()
 obj.newFunction("13579") 

2 个答案:

答案 0 :(得分:2)

我认为问题在于您正在使用mapping。你必须使用它:

self.mapping

答案 1 :(得分:2)

我会做这样的事情:

class CheckFunction(object):
     def __init__(self):
        self.mapping = [6,2,5,5,4,5,6,3,7,6]
     def newFunction(self,code):
        count = 0
        for n in code:
           count += self.mapping[int(n)]
        return count

obj = CheckFunction()
obj.newFunction("13579")

结果:

>>> obj.newFunction('13579')
21
相关问题