为了将名称绑定到外部作用域的变量,我们可以使用global
ornonlocal
关键字,但变量名称事先已知,例如,
x0 = 0
def f1():
x1 = 1
def f2():
x2 = 2
def f3():
x3 = 3
def h():
global x0 # cannot use nonlocal, in case you're curious like me
nonlocal x1, x2, x3
x0 += x0
x1 += x1
x2 += x2
x3 += x3
print(f'x0: {x0}, x1: {x1}, x2: {x2}, x3: {x3}')
return h
return f3()
return f2()
call_h = f1()
call_h() # print on screen: x0: 0, x1: 2, x2: 4, x3: 6
要将名称动态绑定到全局变量,我们可以改用globals()
字典 ( globals()['x0']
)。有没有办法用非局部变量做到这一点?有nonlocals()['x1']
什么东西吗?
编辑1:澄清建议的重复问题不需要修改非本地人,而我的需要。