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

相关推荐
W.A委员会29 分钟前
JS原型链详解
开发语言·javascript·原型模式
m0_3776182330 分钟前
Golang怎么连接MySQL数据库_Golang MySQL连接教程【总结】
jvm·数据库·python
止语Lab39 分钟前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
LN花开富贵1 小时前
【ROS】鱼香ROS2学习笔记一
linux·笔记·python·学习·嵌入式·ros·agv
weixin_586061461 小时前
C#怎么通过反射获取类属性_C#如何动态读取元数据【进阶】
jvm·数据库·python
她说彩礼65万1 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
绿浪19841 小时前
c# 中结构体 的定义字符串字段(性能优化)
开发语言·c#
Jurio.1 小时前
本机开发 + 多机执行的极简远端运行工具
linux·git·python·github·远程工作
skywalk81631 小时前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
overmind1 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python