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

时间:2022-07-05 22:48:14

This question already has an answer here:

这个问题在这里已有答案:

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

以下代码给出了错误UnboundLocalError:赋值前引用的局部变量'Var1':

Var1 = 1Var2 = 0def 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 =- 1function()

How can I fix this? Thanks for any help!

我怎样才能解决这个问题?谢谢你的帮助!

5 个解决方案

#1


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

您可以通过传递参数而不是依赖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 - 1function(1, 1)

#2


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


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.

要解决这个问题,你可以通过将全局Var1放在你的函数中来明确地说它是全局的。

Var1 = 1Var2 = 0def 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 =- 1function()

#4


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 xdef 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 xdef 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]现在将全局变量f更改为3,因此它不再是一个函数。

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

幸运的是,在添加括号进行打印后,它在Python3中工作正常。

#5


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 = 1Var2 = 0def 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 - 1Var1 = 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 & v2return v1 - 1Var1 = function()

#1


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

您可以通过传递参数而不是依赖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 - 1function(1, 1)

#2


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


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.

要解决这个问题,你可以通过将全局Var1放在你的函数中来明确地说它是全局的。

Var1 = 1Var2 = 0def 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 =- 1function()

#4


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 xdef 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 xdef 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]现在将全局变量f更改为3,因此它不再是一个函数。

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

幸运的是,在添加括号进行打印后,它在Python3中工作正常。

#5


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 = 1Var2 = 0def 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 - 1Var1 = 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 & v2return v1 - 1Var1 = function()