nonlocal 与global关键字

Python精进系列:nonlocal 关键字详解_python nonlocal-CSDN博客

nonlocal 关键字用于在嵌套函数中声明一个变量为"非局部变量",即该变量属于外层函数的作用域,而非当前函数的局部作用域
def outer():

x = "外层值"

def inner():

nonlocal x # ✅ 声明 x 是外层变量

x = "内层修改值"

print("内层函数:", x)

inner()

print("外层函数:", x)

outer()

传统方案(全局变量)

count = 0

def counter():

global count

count += 1

return count

print(counter()) # 1

print(counter()) # 2

改进方案(使用 nonlocal

def make_counter():

count = 0

def counter():

nonlocal count

count += 1

return count

return counter

cnt = make_counter()

print(cnt()) # 1

print(cnt()) # 2

x = 10 # 全局变量

def modify():

global x # 声明x为全局变量

x = 20 # 修改全局x的值

modify()

print(x) # 输出20

相关推荐
从零开始学习人工智能1 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
WWJA王文举2 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
卷无止境2 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha13143 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教3 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教3 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境4 小时前
FastAPI 的Admin面板生态
后端·python
qq_448011164 小时前
C语言中的动态内存分配
c语言·开发语言·php
ctlover4 小时前
Streamlit 框架
python
ι:4 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机