Python nonlocal语句有什么作用(在Python 3.0及更高版本中)?
Python nonlocal
官方Python网站上没有文档,help("nonlocal")也无法使用。
help("nonlocal")
比较一下,不使用nonlocal:
nonlocal
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 0
对此,使用nonlocal,其中inner()的x是现在还outer()的x:
inner()
x
outer()
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 2 # global: 0
如果要使用global,它将绑定x到正确的“全局”值:
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 2