Python 3: UnboundLocalError:在赋值之前引用的局部变量[复制]

时间:2022-01-05 03:50:31

This question already has an answer here:

这个问题已经有了答案:

The following code gives the error UnboundLocalError: local variable 'Var1' referenced before assignment:

下面的代码给出了UnboundLocalError的错误:局部变量“Var1”在赋值之前引用:

Var1 = 1
Var2 = 0
def function(): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    Var1 =- 1
function()

How can I fix this? Thanks for any help!

我怎么解决这个问题?感谢任何帮助!

5 个解决方案

#1


27  

You can fix this by passing parameters rather than relying on Globals

您可以通过传递参数来解决这个问题,而不是依赖全局变量。

def function(Var1, Var2): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1
function(1, 1)

#2


215  

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

这是因为,即使Var1存在,您也在函数内的名称Var1上使用赋值语句(在底线中Var1 -= 1)。很自然地,这会在函数的范围内创建一个变量Var1(实际上,a -=或+=只会更新(重新分配)一个现有的变量,但是出于未知的原因(可能是这个上下文中的一致性),Python将其视为一个赋值。Python解释器在模块加载时看到这一点,并决定(正确地),全局范围的Var1不应该在局部范围内使用,这导致在您尝试在本地指定的变量之前引用变量时出现问题。

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

使用全局变量,在需要之外,通常会被Python开发人员所反对,因为这会导致混乱和有问题的代码。但是,如果您想要使用它们来完成您的代码所暗示的内容,您可以简单地添加:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

在函数的顶部。这将告诉Python,您不打算在函数的局部范围内定义Var1或Var2变量。Python解释器在模块加载时看到这一点,并决定(正确地)查找全局范围内上述变量的任何引用。

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python网站对这个常见问题有一个很好的解释。
  • Python 3 offers a related nonlocal statement - check that out as well.
  • Python 3提供了一个相关的非本地语句——检查一下。

#3


46  

If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.

如果在函数中设置变量的值,则python将其理解为创建具有该名称的局部变量。这个局部变量掩盖了全局变量。

In your case, Var1 is considered as a local variable, and it's used before being set, thus the error.

在您的例子中,Var1被认为是一个局部变量,它在被设置之前使用,因此错误。

To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.

要解决这个问题,您可以通过将global Var1放入您的函数中来明确表示它是一个全局变量。

Var1 = 1
Var2 = 0
def function():
    global Var1
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    Var1 =- 1
function()

#4


8  

I don't like this behavior, but this is how Python works. The question has already been answered by others, but for completeness, let me point out that Python 2 has more such quirks.

我不喜欢这种行为,但这是Python的工作方式。这个问题已经得到了其他人的回答,但是为了完整起见,让我指出Python 2有更多这样的怪癖。

def f(x):
    return x

def main():
    print f(3)
    if (True):
        print [f for f in [1, 2, 3]]

main()

Python 2.7.6 returns an error:

Python 2.7.6返回错误:

Traceback (most recent call last):
  File "weird.py", line 9, in <module>
    main()
  File "weird.py", line 5, in main
    print f(3)
UnboundLocalError: local variable 'f' referenced before assignment

Python sees the f is used as a local variable in [f for f in [1, 2, 3]], and decides that it is also a local variable in f(3). You could add a global f statement:

Python将f作为局部变量(f在[1,2,3]中),并决定它也是f(3)中的一个局部变量。你可以添加一个全局f语句:

def f(x):
    return x

def main():
    global f
    print f(3)
    if (True):
        print [f for f in [1, 2, 3]]

main()

It does work; however, f becomes 3 at the end... That is, print [f for f in [1, 2, 3]] now changes the global variable f to 3, so it is not a function any more.

它工作;然而,f最后变成了3…也就是说,在[1,2,3]中对f进行打印,现在将全局变量f改为3,因此它不再是一个函数。

Fortunately, it works fine in Python3 after adding the parentheses to print.

幸运的是,在将括号添加到print之后,它在Python3中运行良好。

#5


1  

Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:

为什么不简单地返回计算值,让调用者修改全局变量。在函数中操作全局变量不是一个好主意,如下所示:

Var1 = 1
Var2 = 0

def function(): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1

Var1 = function()

or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately

或者甚至复制全局变量的本地副本并与它们一起工作,并返回调用者可以适当分配的结果。

def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1

Var1 = function()

#1


27  

You can fix this by passing parameters rather than relying on Globals

您可以通过传递参数来解决这个问题,而不是依赖全局变量。

def function(Var1, Var2): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1
function(1, 1)

#2


215  

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

这是因为,即使Var1存在,您也在函数内的名称Var1上使用赋值语句(在底线中Var1 -= 1)。很自然地,这会在函数的范围内创建一个变量Var1(实际上,a -=或+=只会更新(重新分配)一个现有的变量,但是出于未知的原因(可能是这个上下文中的一致性),Python将其视为一个赋值。Python解释器在模块加载时看到这一点,并决定(正确地),全局范围的Var1不应该在局部范围内使用,这导致在您尝试在本地指定的变量之前引用变量时出现问题。

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

使用全局变量,在需要之外,通常会被Python开发人员所反对,因为这会导致混乱和有问题的代码。但是,如果您想要使用它们来完成您的代码所暗示的内容,您可以简单地添加:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

在函数的顶部。这将告诉Python,您不打算在函数的局部范围内定义Var1或Var2变量。Python解释器在模块加载时看到这一点,并决定(正确地)查找全局范围内上述变量的任何引用。

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python网站对这个常见问题有一个很好的解释。
  • Python 3 offers a related nonlocal statement - check that out as well.
  • Python 3提供了一个相关的非本地语句——检查一下。

#3


46  

If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.

如果在函数中设置变量的值,则python将其理解为创建具有该名称的局部变量。这个局部变量掩盖了全局变量。

In your case, Var1 is considered as a local variable, and it's used before being set, thus the error.

在您的例子中,Var1被认为是一个局部变量,它在被设置之前使用,因此错误。

To solve this problem, you can explicitly say it's a global by putting global Var1 in you function.

要解决这个问题,您可以通过将global Var1放入您的函数中来明确表示它是一个全局变量。

Var1 = 1
Var2 = 0
def function():
    global Var1
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    Var1 =- 1
function()

#4


8  

I don't like this behavior, but this is how Python works. The question has already been answered by others, but for completeness, let me point out that Python 2 has more such quirks.

我不喜欢这种行为,但这是Python的工作方式。这个问题已经得到了其他人的回答,但是为了完整起见,让我指出Python 2有更多这样的怪癖。

def f(x):
    return x

def main():
    print f(3)
    if (True):
        print [f for f in [1, 2, 3]]

main()

Python 2.7.6 returns an error:

Python 2.7.6返回错误:

Traceback (most recent call last):
  File "weird.py", line 9, in <module>
    main()
  File "weird.py", line 5, in main
    print f(3)
UnboundLocalError: local variable 'f' referenced before assignment

Python sees the f is used as a local variable in [f for f in [1, 2, 3]], and decides that it is also a local variable in f(3). You could add a global f statement:

Python将f作为局部变量(f在[1,2,3]中),并决定它也是f(3)中的一个局部变量。你可以添加一个全局f语句:

def f(x):
    return x

def main():
    global f
    print f(3)
    if (True):
        print [f for f in [1, 2, 3]]

main()

It does work; however, f becomes 3 at the end... That is, print [f for f in [1, 2, 3]] now changes the global variable f to 3, so it is not a function any more.

它工作;然而,f最后变成了3…也就是说,在[1,2,3]中对f进行打印,现在将全局变量f改为3,因此它不再是一个函数。

Fortunately, it works fine in Python3 after adding the parentheses to print.

幸运的是,在将括号添加到print之后,它在Python3中运行良好。

#5


1  

Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:

为什么不简单地返回计算值,让调用者修改全局变量。在函数中操作全局变量不是一个好主意,如下所示:

Var1 = 1
Var2 = 0

def function(): 
    if Var2 == 0 and Var1 > 0:
        print("Result One")
    elif Var2 == 1 and Var1 > 0:
        print("Result Two")
    elif Var1 < 1:
        print("Result Three")
    return Var1 - 1

Var1 = function()

or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately

或者甚至复制全局变量的本地副本并与它们一起工作,并返回调用者可以适当分配的结果。

def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1

Var1 = function()