Python 为什么我会在赋值错误之前引用局部变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37651721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:44:01  来源:igfitidea点击:

Why am I getting a local variable referenced before assignment error?

python

提问by Dr.Doom2020

The answer should be 2because first the main()function is called, then the first()function is called, overriding the global variable num = 0 which was defined outside of any functions, therefore rendering it a variable with global scope. Yet I get the following error:

答案应该是2因为首先main()调用函数,然后调用first()函数,覆盖在任何函数之外定义的全局变量 num = 0,因此将其呈现为具有全局作用域的变量。但是我收到以下错误:

UnboundLocalError: local variable 'num' referenced before assignment  

Why am I getting this error?

为什么我收到这个错误?

def first():
    num = num + 1

def main():
    num = 1
    first()
    print(num)

num = 0

num_result = main()

print(num_result) 

回答by Jonas Sch?fer

The OP wrote (emphasis mine):

OP写道(强调我的):

The answer should be 2 because first the main() function is called, then the first() function is called, overriding the global variable.

答案应该是 2,因为首先调用 main() 函数,然后调用 first() 函数,覆盖全局变量

It is not overriding the global variable. Unless you explicitly specify a variable as global, if there is any assignment to the variable in a function, it is assumed to be local. See also the python tutorial on defining functionswhere it states (emphasis mine):

它不会覆盖全局变量。除非您明确指定一个变量为全局变量,否则如果在函数中对该变量进行任何赋值,则假定它是局部变量。另请参阅有关定义函数Python 教程(重点是我的):

More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

更准确地说,函数中的所有变量赋值都将值存储在本地符号表中;而变量引用首先查看局部符号表,然后是封闭函数的局部符号表,然后是全局符号表,最后是内置名称表。因此,全局变量不能在函数内直接赋值(除非在全局语句中命名),尽管它们可以被引用。

and the documentation of the globalstatement(if anyone using Python 3 is looking at this, please also take a look at the (compared to global) very useful nonlocalstatementand its PEP 3104).

以及该语句文档global(如果有人使用 Python 3 正在查看此内容,请同时查看(与global)非常有用的nonlocal语句及其PEP 3104 相比)。

To "fix" your code:

要“修复”您的代码:

def first():
    global num
    num = num + 1

def main():
    global num
    num = 1
    first()
    print(num)

num = 0

num_result = main()

print(num_result) 

Do not use global variables in this way please. @LutzHorn has shown in his answer how to do it right.

请不要以这种方式使用全局变量。@LutzHorn 在他的回答中展示了如何正确地做

The reason to avoid global variables is that their effect is hard to test for, and as soon as code gets complex enough, hard to reason about. If every function modifies global variables instead of properly taking parameters and returning values, understanding what the code actually does is hard as soon as one has more than a week or so of distance from it.

避免使用全局变量的原因是它们的效果很难测试,而且一旦代码变得足够复杂,就很难推理。如果每个函数都修改全局变量而不是正确地获取参数和返回值,那么一旦距离它一个多星期左右的距离,就很难理解代码实际做了什么。

回答by Jonas Sch?fer

Inside first, numis not known. Use arguments and returnstatements.

里面firstnum不得而知。使用参数和return语句。

def first(num):
    return num + 1

def main():
    num = 1
    num = first(num)
    return num

num = 0

num_result = main()

print(num_result)

回答by Paul

This is a scope error. In first, there is no num before you try to add one to it. You can call a variable in a bloc if it is declared in this bloc, in an upper bloc or if it is declared global.

这是一个范围错误。首先,在您尝试向其中添加一个之前,没有 num。如果一个变量在这个 bloc 中、在一个上层 bloc 中或者如果它被声明为 global,你可以在 bloc 中调用它。

To pass variables, you can use arguments of the function:

要传递变量,您可以使用函数的参数:

def first(num):
    return num + 1

def main():
    shmilblik = first(1)
    print(shmilblik)

回答by Matthias Schreiber

"num" is not defined in the function "first". It is not a global variable, it is out of the scope of "first". To make it global just edit your function like this:

函数“first”中没有定义“num”。它不是全局变量,它超出了“第一”的范围。要使其全局化,只需像这样编辑您的函数:

def first():
    global num
    num = num + 1

Using globals is bad practice in my opinion. you could achieve the same by using parameters and a return like this:

在我看来,使用全局变量是不好的做法。您可以通过使用参数和这样的返回来实现相同的效果:

def first(num):
    return num + 1

def main(num):
    num = 1
    num = first(num)
    print(num)
    return num

num = 0

num_result = main(num)

print(num_result) 

回答by Matthias Schreiber

The variable num is just initialized in the main-method, you're not initializing it in the first()-Method. So you've to hand it over to the first()-Method.

变量 num 只是在 main-method 中初始化,你没有在 first()-Method 中初始化它。所以你必须把它交给 first()-Method。

def first(num):
    return num + 1

def main():
    num = 1
    num = first(num)
    return num

num = 0

num_result = main()

print(num_result)