python - 嵌入式函数中的全局变量
问题描述
我有以下片段:
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
这种模式似乎会被打破。将变量定义为全局变量(如此处)或将其作为参数传递给内部函数均未按预期工作。基本上,标量变量保持不变。我需要做什么才能获得具有此类标量值的所需行为?
解决方案
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.
推荐阅读
- c# - 如何使用windows窗体c#删除文件
- html - 如何使此图像位于文本下方?
- daml - 行使选择权时如何获取当前的合约ID
- google-cloud-storage - Google Cloud Storage 库中的更新
- usb - 如何在新的 USB 设备上创建和加载设备描述符以便 Windows 识别它?
- python - 如何从python中的60GB文本文件中读取与特定行号相对应的数据?
- python - 如何使用两个索引数组扩展 numpy 数组
- android - 我想从 sql lite 数据库中获取数据并使用由组名填充的列表视图将其显示在图形视图上
- c++ - glDrawPixels 没有填满窗口
- javascript - Javascript AppendChild 问题