You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何在循环中使用外部作用域变量定义函数?

问题原因

nonlocal关键字的作用是引用外层函数作用域中的变量,而非循环迭代的临时作用域。你的代码里没有外层函数,obj是循环每次迭代时创建的局部变量,不属于任何外层函数作用域,所以nonlocal找不到对应的变量绑定,触发语法错误。

解决方案

方案1:直接移除nonlocal声明

因为你只是修改可变对象(字典)的内部元素,而非重新赋值obj本身,Python允许函数直接访问并修改外层作用域的可变对象,不需要额外声明。修改后的代码如下:

for i in range(5):
    obj = {"start": i}
    def update():
        obj["next"] = obj["start"] + 1
        print(obj)
    update()

运行后会输出:

{'start': 0, 'next': 1}
{'start': 1, 'next': 2}
{'start': 2, 'next': 3}
{'start': 3, 'next': 4}
{'start': 4, 'next': 5}

方案2:若需保存update函数后续调用

如果要把循环中定义的update函数保存下来(比如存入列表),后续调用时要注意循环变量的绑定问题——默认情况下所有函数会引用最后一次迭代的obj。可以用默认参数捕获当前迭代的obj:

updates = []
for i in range(5):
    obj = {"start": i}
    # 通过默认参数绑定当前迭代的obj
    def update(obj=obj):
        obj["next"] = obj["start"] + 1
        print(obj)
    updates.append(update)

# 后续调用所有保存的函数
for func in updates:
    func()
补充:nonlocal的正确使用场景

nonlocal仅用于嵌套函数中,引用外层函数的变量,示例:

def outer_func():
    count = 0
    def inner_func():
        nonlocal count
        count += 1
        print(count)
    inner_func()
    inner_func()

outer_func()

运行输出:

1
2

内容的提问来源于stack exchange,提问作者Andrej Tzutzu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 06:06:21