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 小时前
Python 爬虫进阶:如何利用反射机制破解常见反爬策略
开发语言·爬虫·python·python爬虫·数据爬虫·爬虫python
躺平大鹅2 小时前
5个实用Python小脚本,新手也能轻松实现(附完整代码)
python
阿猿收手吧!2 小时前
【C++】异步编程:std::async终极指南
开发语言·c++
yukai080082 小时前
【最后203篇系列】039 JWT使用
python
小程故事多_802 小时前
Agent Infra核心技术解析:Sandbox sandbox技术原理、选型逻辑与主流方案全景
java·开发语言·人工智能·aigc
沐知全栈开发2 小时前
SQL 日期处理指南
开发语言
黎雁·泠崖2 小时前
【魔法森林冒险】3/14 Allen类(一):主角核心属性与初始化
java·开发语言
黎雁·泠崖2 小时前
【魔法森林冒险】1/14 项目总览:用Java打造你的第一个回合制冒险游戏
java·开发语言
独好紫罗兰2 小时前
对python的再认识-基于数据结构进行-a006-元组-拓展
开发语言·数据结构·python
Dfreedom.2 小时前
图像直方图完全解析:从原理到实战应用
图像处理·python·opencv·直方图·直方图均衡化