名称 意义 简写
Local 局部作用域 L
Enclosed 嵌套作用域 E
Global 全局作用域 G
Built-in 内置作用域 B

python 在函数里面的查找分为4种——LEGB,按照这个顺序进行查找。
10 python变量作用域与闭包 - 图1
locals -> enclosing function -> globals -> builtins

L/G

函数的形参和内部变量都在locals中

  1. def func(x):
  2. f = x
  3. print(f)
  4. print(locals())
  5. func('123')
  6. >>>123
  7. {'f': '123', 'x': '123'}

在局部作用域中添加 global 声明将变量存储在G中

  1. def func(x):
  2. global f
  3. f = x
  4. print(f)
  5. print(locals())
  6. print(locals())
  7. func('123')
  8. print(f)
  9. print(x)
  10. >>>123
  11. {'x': '123'}
  12. {'__name__': '__main__', ..., 'f': '123'}
  13. 123
  14. Traceback (most recent call last):
  15. File "g:\Leetcode vscode\demo.py", line 9, in <module>
  16. print(x)
  17. NameError: name 'x' is not defined

此时L中只有x。而f出现在G中。

E 闭包

闭包是什么

闭包是函数式编程的重要语法结构。闭包也是一种组织代码的结构,他同样提高了代码的可重复使用性。
当一个内嵌函数引用其外部作用域的变量,我们就会得到一个闭包。

  1. 必须有一个内嵌函数
  2. 内嵌函数必须引用外部函数中的变量
  3. 外部函数的返回值必须是内嵌函数

闭包每次运行时可以记住引用的外部作用域的变量值。闭包

  1. def func():
  2. x = 5
  3. def inner():
  4. nonlocal x
  5. x += 1
  6. return x
  7. return inner
  8. f = func()
  9. print(f()) # 6
  10. print(f()) # 7
  11. print(f()) # 8

nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量.

def func():
    x = 'enclosed value'
    print(x)    # enclosed value
    def inner():
        nonlocal x
        x = 'inner'
        print(x)    # inner

    inner()
    print(x)    # inner

B

builtins 是内置模块不可更改
dir(__builtins__)