[英]Global variables in embedded functions
I have the following snippet: 我有以下片段:
def test ():
num_sum = 0
def inner_test ():
global num_sum
num_sum += 1
inner_test()
return num_sum
When I run test() I get: 当我运行test()时,我得到:
NameError: name 'num_sum' is not defined NameError:名称“ num_sum”未定义
I was expecting that the inner function would change the value of the num_sum
variable defined in the outer function. 我期望内部函数会更改外部函数中定义的num_sum
变量的值。 Basically, I need a global variable to increment in an inner function which I may call recursively. 基本上,我需要一个全局变量来递增一个内部函数,该函数可以递归调用。
I noticed that this pattern works well with collections (lists, dictionaries) even if I don't define the variable as global (but pass it as a parameter to the inner function). 我注意到,即使我没有将变量定义为全局变量(而是将其作为参数传递给内部函数),该模式也可以很好地用于集合(列表,字典)。
However, with scalar values like int
this pattern seems to break. 但是,对于类似int
标量值,此模式似乎会中断。 Neither defining the variable as global (as is here) nor passing it as a parameter to the inner function works as intended. 既不将变量定义为全局变量(如此处所示),也没有将其作为参数传递给内部函数都无法按预期工作。 Basically, the scalar variable stays unchanged. 基本上,标量变量保持不变。 What do I need to do to get the desired behaviour with such scalar values? 我需要怎么做才能获得具有这种标量值的预期行为?
you need nonlocal
instead of global
. 您需要nonlocal
而不是global
。 your num_sum
is not a global variable (will not be found in globals()
). 您的num_sum
不是全局变量(在globals()
找不到)。 nonlocal
will instruct python not to search for it in the global namespace, but in the nearest namespace. nonlocal
会指示python不要在全局名称空间中搜索它,而是在最近的名称空间中搜索。 the order is LEGB: Local, Enclosed, Global, Built-in . 顺序为LEGB:本地,封闭,全局,内置 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.