nonlocal关键字

nonlocal适用于嵌套函数中内部函数修改外部变量的值

如果没有使用以上关键字,对全局变量或者外部变量进行修改,python会默认将全局变量隐藏起来

 1 #例1:
 2 
 3 def outside():
 4   var = 5
 5   def inside():
 6     var = 3
 7     print(var)
 8 
 9   inside()
10 outside()
11 
12 #例2:
13 
14 def outside():
15   var = 5
16   def inside():
17     print(var)  inside函数改变了var所以python将var隐藏了起来,这里的print找不到var因而报错。
18     var = 3
19 
20   inside()
21 outside()

例1不会显示报错,但是例2会

猜你喜欢

转载自www.cnblogs.com/ducklu/p/8960921.html
今日推荐