在Python中取消绑定本地错误我无法动摇! [英] Unbound Local error in Python I can't shake!

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

问题描述

http://pastie.org/1966237

我不断收到一个未绑定的本地错误。我不明白为什么会发生这种情况,如果程序运行正确,应该直接进入主函数中print_et_list函数的第二个赋值,循环自身而不会实际循环。该程序仅在hey_user函数中使用sys.exit()退出。

I keep getting an unbound local error. I don't understand why it occurs, if the program is running right, it should go straight into the second assignment of the print_et_list function within the main function, looping itself without actually looping. The program only quits using sys.exit() in the hey_user function.

我将整个程序包含在上下文中,并不算太长。让我知道,如果你想看看我在程序中使用的文本文件,但我确信这不太可能是问题的根源。

I included the whole program for context, it isn't too long. Let me know if you want to have a look at the text files I use in the program, however I'm sure it's unlikely that it is the source of the problem.

推荐答案

当您设置本地变量的值之前,UnboundLocalError会发生。为什么得分是局部变量而不是全局变量?因为你把它设置在函数中。考虑这两个功能:

UnboundLocalError happens when you read the value of a local variable before you set it. Why is score a local variable rather than a global variable? Because you set it in the function. Consider these two functions:

def foo():
    print a

vs

def bar():
    a = 1
    print a

在foo()中,a是全局的,因为它没有设置在函数内。在bar()中,a是本地的。现在考虑这个代码:

In foo(), a is global, because it is not set inside the function. In bar(), a is local. Now consider this code:

def baz():
    print a
    a = 1

这里,a在函数内设置,因此它是本地的。但是在打印声明的时候还没有设置,所以你得到了UnboundLocalError。

Here, a is set within the function, so it's local. But it hasn't been set at the time of the print statement, so you get the UnboundLocalError.

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

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