chenlxhf 2020-06-25
dict
来理解(事实上也是这么实现的)print()
,type()
之类global
,nonlocal
修饰的情况下a = 1 def outer_function(): a = 2 def nested_function(): a = 3 print(f"I am in Nested_function {a}") nested_function() print(f"I am in outer_function {a}") outer_function() print(f"I am not in outer_function {a}") # I am in Nested_function 3 # I am in outer_function 2 # I am not in outer_function 1
global
修改的情况下,可以看出我们修改了全局变量的a
,a = 1 def outer_function(): a = 2 def nested_function(): global a a = 3 print(f"I am in Nested_function {a}") nested_function() print(f"I am in outer_function {a}") outer_function() print(f"I am not in outer_function {a}") # I am in Nested_function 3 # I am in outer_function 2 # I am not in outer_function 3
nonlocal
修改的情况下,可以看出我们修改的是父函数中的a
,这也符合我们之前所说的查找顺序,这里是从嵌套函数的Local Namespaces–>父函数的Local Namespacesa = 1 def outer_function(): a = 2 def nested_function(): nonlocal a a = 3 print(f"I am in Nested_function {a}") nested_function() print(f"I am in outer_function {a}") outer_function() print(f"I am not in outer_function {a}") # I am in Nested_function 3 # I am in outer_function 3 # I am not in outer_function 1