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至将它标记为只是为了安全并确保它在我所有方法的范围内。

4

2 回答 2

4

您需要将该行global currentTok放入您的功能,而不是主模块。

currentTok=0                     

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

global关键字告诉您的函数它需​​要在全局范围内查找该变量。

于 2013-02-26T16:51:22.210 回答
2

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

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

于 2013-02-26T16:51:41.700 回答