未绑定本地错误 [英] Unbound Local Error

查看:37
本文介绍了未绑定本地错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中使用以下代码不断收到未绑定的本地错误:

  xml = []全球潮流currentTok = 0def需求:如果tokenObjects [currentTok + 1] .category == s:currentTok + = 1返回tokenObjects [currentTok]别的:引发Exception(类型不正确")def compileExpression():xml.append(< expression>")xml.append(compileTerm(currentTok))打印当前而op中的currentTok< len(tokenObjects)和tokenObjects [currentTok] .symbol:xml.append(tokenObjects [currentTok] .printTok())currentTok + = 1打印当前xml.append(compileTerm(currentTok))xml.append(</expression>")def compileTerm():string =< term>"category = tokenObjects [currentTok] .category如果category =="integerConstant"或category =="stringConstant"或category =="identifier":string + = tokenObjects [currentTok] .printTok()currentTok + = 1字符串+ =</term>"返回字符串compileExpression()打印xml 

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

  UnboundLocalError:分配前已引用局部变量"currentTok". 

这对我来说毫无意义,因为我明确地将 currentTok 初始化为代码的第一行,甚至为了安全起见,我甚至将其标记为 global 确保它在我所有方法的范围之内.

解决方案

您需要将 global currentTok 行放入您的 function 中,而不是主模块中.

>

  currentTok = 0def需求:全球潮流如果tokenObjects [currentTok + 1] .category == s:# 等等. 

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

I keep getting an unbound local error with the following code in 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

The following is the exact error that I get:

UnboundLocalError: local variable 'currentTok' referenced before assignment.

This makes no sense to me as I clearly initialize currentTok as one of the first lines of my code, and I even labeled it as global just to be safe and make sure it was within the scope of all my methods.

解决方案

You need to put the line global currentTok into your function, not the main module.

currentTok=0                     

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

The global keyword tells your function that it needs to look for that variable in the global scope.

这篇关于未绑定本地错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆