Python local variables behaving strangely
本问题已经有最佳答案,请猛点这里访问。
考虑以下代码:
1 2 3 4 5 6 7 8 9 10 | def g(): a = {} b = 0 def f(): a[0] = b f() print(a) return a a = g() print(a) |
它在执行时提供以下输出:
1 2 | {0: 0} {0: 0} |
但如果我尝试更新EDOCX1中的
1 2 3 4 5 6 7 8 9 10 11 | def g(): a = {} b = 0 def f(): a[0] = b b+=1 f() print(a) return a a = g() print(a) |
它引发以下错误:
1 | UnboundLocalError: local variable 'b' referenced before assignment |
这是预期的吗?我需要在
显式地将
1 2 3 4 5 6 7 8 9 | def g(): a = {} b = 0 def f(a, b): a[0] = b b += 1 return b b = f(a, b) return a |
您需要使用
1 2 3 4 5 6 7 8 9 10 11 12 | def g(): a = {} b = 0 def f(): nonlocal b a[0] = b b+=1 f() print(a) return a a = g() print(a) |
这是因为