未绑定的局部变量错误
我在用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
,就是为了确保它在我所有的方法中都能用。
2 个回答
2
你需要在函数内部声明它为全局变量,而不是在全局范围内声明。
否则,Python解释器会看到你在函数里使用这个变量,认为它是一个局部变量。当你第一次引用它而不是给它赋值时,解释器就会报错。
4
你需要把这一行 global currentTok
放到你的 函数 里面,而不是放在主模块里。
currentTok=0
def demand(s):
global currentTok
if tokenObjects[currentTok+1].category==s:
# etc.
global
这个关键词是告诉你的函数,它需要在全局范围内去查找这个变量。