Python非本地语句
发布于 2021-02-02 23:18:43
Python nonlocal
语句有什么作用(在Python 3.0及更高版本中)?
官方Python网站上没有文档,help("nonlocal")
也无法使用。
关注者
0
被浏览
76
1 个回答
-
比较一下,不使用
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
: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