| 名称 | 意义 | 简写 |
|---|---|---|
| Local | 局部作用域 | L |
| Enclosed | 嵌套作用域 | E |
| Global | 全局作用域 | G |
| Built-in | 内置作用域 | B |
python 在函数里面的查找分为4种——LEGB,按照这个顺序进行查找。
locals -> enclosing function -> globals -> builtins
L/G
函数的形参和内部变量都在locals中
def func(x):f = xprint(f)print(locals())func('123')>>>123{'f': '123', 'x': '123'}
在局部作用域中添加 global 声明将变量存储在G中
def func(x):global ff = xprint(f)print(locals())print(locals())func('123')print(f)print(x)>>>123{'x': '123'}{'__name__': '__main__', ..., 'f': '123'}123Traceback (most recent call last):File "g:\Leetcode vscode\demo.py", line 9, in <module>print(x)NameError: name 'x' is not defined
E 闭包
闭包是什么
闭包是函数式编程的重要语法结构。闭包也是一种组织代码的结构,他同样提高了代码的可重复使用性。
当一个内嵌函数引用其外部作用域的变量,我们就会得到一个闭包。
- 必须有一个内嵌函数
- 内嵌函数必须引用外部函数中的变量
- 外部函数的返回值必须是内嵌函数
闭包每次运行时可以记住引用的外部作用域的变量值。闭包
def func():x = 5def inner():nonlocal xx += 1return xreturn innerf = func()print(f()) # 6print(f()) # 7print(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__)
