首页 > 解决方案 > 嵌入式函数中的全局变量

问题描述

我有以下片段:

def test ():
  num_sum = 0
  def inner_test ():
    global num_sum
    num_sum += 1
  inner_test()
return num_sum

当我运行 test() 我得到:

NameError:未定义名称“num_sum”

我期待内部函数会改变num_sum外部函数中定义的变量的值。基本上,我需要一个全局变量来增加我可以递归调用的内部函数。

我注意到即使我没有将变量定义为全局变量(但将其作为参数传递给内部函数),这种模式也适用于集合(列表、字典)。

然而,对于像这种模式这样的标量值,int这种模式似乎会被打破。将变量定义为全局变量(如此处)或将其作为参数传递给内部函数均未按预期工作。基本上,标量变量保持不变。我需要做什么才能获得具有此类标量值的所需行为?

标签: pythonpython-3.xglobal-variables

解决方案


you need nonlocal instead of global. your num_sum is not a global variable (will not be found in globals()). nonlocal will instruct python not to search for it in the global namespace, but in the nearest namespace. the order is LEGB: Local, Enclosed, Global, Built-in.


推荐阅读