关于内嵌函数和闭包
>>> def test(x):a=x+1
print(a)
def test2(a):
nonlocal x
x=x
return a,x
return test2(x)
>>> test(1)
2
(1, 1)
>>> test(2)
3
(2, 2)
>>>
请问为什么在test2函数之中,a的输出值不是在test函数中定义的x+1,而是a等于了x?
通过print输出了a在test函数中的值,可见此时完全正常,a=x+1,符合目标公式
但是当将a输入被嵌套的函数test2之后,a却莫名的改为了等同于x
这是为什么?又怎么解决?
你 return test2(x) 传入的是 x 的值,而不是 a 的值
test2 函数因为 参数设置为 a ,那么此时屏蔽了 test 相对 test2 的全局变量 a ,此时 a = x
所以最后你返回 a,x 都是相等的值 ,把 return test2(x) 改成 return test2(a) 就可以了
Twilight6 发表于 2021-6-4 16:21
你 return test2(x) 传入的是 x 的值,而不是 a 的值
test2 函数因为 参数设置为 a ,那么此时屏蔽了...
return后的值忘改了,没发现
页:
[1]