gpt4 book ai didi

python - Python 2.x 中的 nonlocal 关键字

转载 作者:IT老高 更新时间:2023-10-28 21:06:14 24 4
gpt4 key购买 nike

我正在尝试在 Python 2.6 中实现一个闭包,我需要访问一个非局部变量,但似乎这个关键字在 python 2.x 中不可用。在这些版本的 python 中,应该如何访问闭包中的非局部变量?

最佳答案

内部函数可以读取 2.x 中的非局部变量,只是不能重新绑定(bind)它们。这很烦人,但你可以解决它。只需创建一个字典,并将您的数据作为元素存储在其中。不禁止内部函数变异非局部变量引用的对象。

使用 Wikipedia 中的示例:

def outer():
d = {'y' : 0}
def inner():
d['y'] += 1
return d['y']
return inner

f = outer()
print(f(), f(), f()) #prints 1 2 3

关于python - Python 2.x 中的 nonlocal 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3190706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com