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
原文:https://www.cnblogs.com/MartinLwx/p/13191464.html