Python全栈之路----函数进阶----作用域的查找空间

n = 10

def func():
    n = 20
    print('func:',n)

    def func2():
        n = 30
        print('func2:',n)

        def func3():
            print('func3:',n)

        func3()

    func2()

func()

问题:在func3()里打印的n的值是多少?   30

LEGB代表名字查找顺序:locals -> enclosing function -> globals -> _builtins_

  • locals 是函数内的名字空间,包括局部变量和形参
  • enclosing 是外部嵌套函数的名字空间
  • globals 全局变量,函数定义所在模块的名字空间
  • builtins 内置模块的名字空间

猜你喜欢

转载自www.cnblogs.com/Moxiaoyu666/p/10387314.html
今日推荐