为什么我不能在Python中设置全局变量? [英] Why can't I set a global variable in Python?
问题描述
全局变量如何在Python中工作?我知道全局变量是邪恶的,我只是在试验。
这在python中不起作用:
<$ p如果G是无:
G = 1
foo()
$ f
$ f $ ()
出现错误:
UnboundLocalError:赋值前引用的局部变量'G'
我做错了吗?
您需要 global
声明:
<$ p $如果G是无:
G = 1
在Python中,默认分配给的变量成为局部变量。您需要使用 global
将其声明为全局变量。另一方面,您引用但未分配给的变量不会自动成为局部变量。这些变量引用了封闭范围中最接近的变量。
Python 3.x引入了 nonlocal
语句,类似于 global
,但将变量绑定到最近的封闭范围。例如:
def foo():
x = 5
def bar():
非本地x
x = x * 2
bar()
返回x
这个函数在被调用时返回10。
How do global variables work in Python? I know global variables are evil, I'm just experimenting.
This does not work in python:
G = None
def foo():
if G is None:
G = 1
foo()
I get an error:
UnboundLocalError: local variable 'G' referenced before assignment
What am I doing wrong?
You need the global
statement:
def foo():
global G
if G is None:
G = 1
In Python, variables that you assign to become local variables by default. You need to use global
to declare them as global variables. On the other hand, variables that you refer to but do not assign to do not automatically become local variables. These variables refer to the closest variable in an enclosing scope.
Python 3.x introduces the nonlocal
statement which is analogous to global
, but binds the variable to its nearest enclosing scope. For example:
def foo():
x = 5
def bar():
nonlocal x
x = x * 2
bar()
return x
This function returns 10 when called.
这篇关于为什么我不能在Python中设置全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!