随手记-python3中nonlocal的作用
**为什么需要 nonlocal**
核心原因:Python 的变量作用域规则
Python 中,赋值操作会创建新变量,而不是修改外部变量。
> 没有 nonlocal 的问题
```python
def outer():
counter = 0 # 外部变量
def inner():
counter = 10 # 创建了一个新的局部变量,没有修改外部的 counter
print(f"内部 counter: {counter}")
print(f"调用前: {counter}") # 输出: 0
inner() # 输出: 内部 counter: 10
print(f"调用后: {counter}") # 输出: 0(外部 counter 没有被修改)
outer()
```
问题:counter = 10 在 inner() 中创建了一个新的局部变量,而不是修改外部的 counter。
> 使用 nonlocal 修复
```python
def outer():
counter = 0 # 外部变量
def inner():
nonlocal counter # 声明使用外部变量
counter = 10 # 修改外部的 counter
print(f"内部 counter: {counter}")
print(f"调用前: {counter}") # 输出: 0
inner() # 输出: 内部 counter: 10
print(f"调用后: {counter}") # 输出: 10(外部 counter 被修改了)
outer()
```
---
**Python 变量查找规则(LEGB)**
- Python 按以下顺序查找变量:
- Local(局部)- 当前函数内部
- Enclosing(嵌套)- 外部函数
- Global(全局)- 模块级别
- Built-in(内置)- Python 内置
类比理解
- 读取外部变量: 像看别人的书,可以看但不能改
- 修改外部变量: 像在别人的书上写字,需要先获得许可(nonlocal)
- 赋值创建新变量: 像自己买了一本新书,和别人那本没关系
为什么这样设计:为了避免意外修改外部变量,提高代码安全性和可维护性。