操作变量时的 UnboundLocalError 产生不一致的行为 [英] UnboundLocalError when manipulating variables yields inconsistent behavior

查看:45
本文介绍了操作变量时的 UnboundLocalError 产生不一致的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,以下代码有效:

In Python, the following code works:

a = 1
b = 2

def test():
    print a, b

test()

以下代码有效:

a = 1
b = 2

def test():
    if a == 1:
        b = 3
    print a, b

test()

但以下方法不起作用:

a = 1
b = 2

def test():
    if a == 1:
        a = 3
    print a, b

test()

最后一个块的结果是一个 UnboundLocalError 消息,说明在赋值之前引用了 a.

The result of this last block is an UnboundLocalError message, saying a is referenced before assignment.

我知道如果我在 test() 定义中添加 global a ,我可以使最后一个块工作,所以它知道哪个 a我正在谈论.

I understand I can make the last block work if I add global a in the test() definition, so it knows which a I am talking about.

为什么在为 b 分配新值时没有出现错误?

Why do I not get an error when assigning a new value to b?

我是否创建了一个本地 b 变量,它不会因为我没有在赋值前尝试引用它而对我大喊大叫?

Am I creating a local b variable, and it doesn't yell at me because I'm not trying to reference it before assignment?

但是如果是这样的话,为什么我可以在第一个块的情况下print a, b,而不必事先声明global a, b?

But if that's the case, why can I print a, b in the case of the first block, without having to declare global a, b beforehand?

推荐答案

让我给你链接到 docs 明确提到的地方.

Let me give you the link to the docs where it is clearly mentioned.

如果一个变量在函数体内的任何位置赋值一个新值,它被假定为一个局部>.

If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local.

(强调我的)

因此你的变量 a 是一个局部变量而不是全局变量.这是因为你有一个赋值语句,

Thus your variable a is a local variable and not global. This is because you have a assignment statement,

a = 3

在代码的第三行.这使得 a 成为局部变量.并且在声明之前引用局部变量会导致一个错误,即 UnboundLocalError.

In the third line of your code. This makes a a local variable. And referring to the local variable before declaration causes an error which is an UnboundLocalError.

但是在您的第二个代码块中,您没有进行任何此类赋值语句,因此您不会收到任何此类错误.

However in your 2nd code block, you do not make any such assignment statements and hence you do not get any such error.

另一个有用的链接是this

在函数或方法中对局部变量进行引用,但没有值绑定到该变量时引发.

Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.

因此,您指的是您在下一行中创建的局部变量.

Thus you are referring to the local variable you create in the next line.

有两种方法可以防止这种情况

To prevent this there are two ways

  • 好方法 - 传递参数

  • Good way - Passing parameters

将您的函数定义为 def test(a): 并将其调用为 test(a)

Define your function as def test(a): and call it as test(a)

糟糕的方法 - 使用 global

Bad way - Using global

在函数调用的顶部有一行 global a.

Have a line global a at the top of your function call.

Python 范围规则有点棘手!你需要掌握它们才能掌握这门语言.查看这个

Python scoping rules are a little tricky! You need to master them to get hold of the language. Check out this

这篇关于操作变量时的 UnboundLocalError 产生不一致的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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