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

相关推荐
万粉变现经纪人12 分钟前
如何解决 pip install 安装报错 ModuleNotFoundError: No module named ‘tokenizers’ 问题
python·selenium·测试工具·scrapy·beautifulsoup·fastapi·pip
西阳未落2 小时前
C++基础(21)——内存管理
开发语言·c++·面试
编程武士2 小时前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao2 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
callJJ2 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di
hsjkdhs4 小时前
万字详解C++之构造函数析构函数
开发语言·c++
Lin_Aries_04214 小时前
容器化简单的 Java 应用程序
java·linux·运维·开发语言·docker·容器·rpc
傻啦嘿哟5 小时前
Python SQLite模块:轻量级数据库的实战指南
数据库·python·sqlite
Q_Q5110082855 小时前
python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
spring boot·python·django·flask·uni-app·node.js·php
XueminXu5 小时前
Python读取MongoDB的JSON字典和列表对象转为字符串
python·mongodb·json·pymongo·mongoclient·isinstance·json.dumps