2013-02-26 89 views
0

我一直在python获得非绑定本地错误与下面的代码:非绑定本地错误

xml=[]  
global currentTok 
currentTok=0      

def demand(s): 
    if tokenObjects[currentTok+1].category==s: 
     currentTok+=1 
     return tokenObjects[currentTok] 
    else: 
     raise Exception("Incorrect type") 

def compileExpression(): 
    xml.append("<expression>") 
    xml.append(compileTerm(currentTok)) 
    print currentTok 
    while currentTok<len(tokenObjects) and tokenObjects[currentTok].symbol in op: 
     xml.append(tokenObjects[currentTok].printTok()) 
     currentTok+=1 
     print currentTok 
     xml.append(compileTerm(currentTok)) 
    xml.append("</expression>") 

def compileTerm(): 
    string="<term>" 
    category=tokenObjects[currentTok].category 
    if category=="integerConstant" or category=="stringConstant" or category=="identifier": 
     string+=tokenObjects[currentTok].printTok() 
     currentTok+=1 
    string+="</term>" 
    return string 

compileExpression() 
print xml 

下面是我得到确切的错误:

UnboundLocalError: local variable 'currentTok' referenced before assignment. 

这是没有意义的,我因为我明确将currentTok初始化为我的代码的第一行,并且我甚至将其标记为global以保证安全,并确保它在我所有方法的范围内。

+0

看看http://stackoverflow.com/questions/929777/why-does-assigning-to-my-global-variables-not-work-in-python特别是接受的答案。 – Ketouem 2013-02-26 16:53:00

回答

4

您需要将行global currentTok放入您的函数,而不是主模块。

currentTok=0      

def demand(s): 
    global currentTok 
    if tokenObjects[currentTok+1].category==s: 
     # etc. 

global关键字告诉你的函数,它需要寻找在全球范围内该变量。

2

您需要在函数定义中声明它是全局的,而不是在全局范围内。

否则,Python解释器会在函数内部使用它,假定它是一个局部变量,然后在您做的第一件事是引用它而不是分配给它时抱怨。