Python闭包的使用方法
作者:程序员班长 时间:2022-11-27 07:45:07
1.闭包的定义和使用
当返回的内部函数使用了外部函数的变量就形成了闭包
闭包可以对外部函数的变量进行保存,还可以提高代码的可重用性
实现闭包的标准格式:
1.函数嵌套
2.内部函数使用外部函数的变量或参数
3.外部函数返回了内部函数
'''
当返回的内部函数使用了外部函数的变量就形成了闭包
闭包可以对外部函数的变量进行保存,还可以提高代码的可重用性
实现闭包的标准格式:
1.函数嵌套
2.内部函数使用外部函数的变量或参数
3.外部函数返回了内部函数
'''
# 定义一个闭包
def outer(): # 外部函数
n=1
def inner(): # 内部函数
print(n)
# 外函数返回内函数的引用(不用带括号哈)
return inner
outer() # 调用外函数不会执行内函数
# inner() # 不能直接调用内函数
ret=outer() # 把内函数的引用给ret
print(ret)
ret()
# 闭包的使用
def person(name):
def say(msg):
print(f'{name} say: {msg}')
return say
tom=person('Tom')
rose=person('Rose')
tom('Hello')
rose('World')
2.闭包内函数修改外函数定义的变量(加nonlocal)
def outer():
n=1
def inner():
nonlocal n # 不加会报错,列表、字典、元祖不用加
n=n+10
print(n)
print(n) # 输出1
return inner
fun=outer()
fun() # 输出11
fun() # 输出21
来源:https://kantlee.blog.csdn.net/article/details/122684641
标签:Python,闭包,使用
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用生成器来改写直接返回列表的函数方法
2022-04-24 15:36:08
![](https://img.aspxhome.com/file/2023/5/105575_0s.png)
vue-cli项目中遇到的eslint的坑及解决
2024-05-29 22:23:22
pytorch 准备、训练和测试自己的图片数据的方法
2021-02-27 13:54:35
![](https://img.aspxhome.com/file/2023/0/91940_0s.png)
python编程之requests在网络请求中添加cookies参数方法详解
2023-07-03 00:48:23
使用Python爬了4400条淘宝商品数据,竟发现了这些“潜规则”
2021-10-24 09:49:02
![](https://img.aspxhome.com/file/2023/7/128507_0s.jpg)
谈一谈基于python的面向对象编程基础
2021-09-09 11:04:39
![](https://img.aspxhome.com/file/2023/3/63543_0s.png)
django安装xadmin及问题解决
2023-06-24 03:41:09
![](https://img.aspxhome.com/file/2023/8/131188_0s.png)
Linux下安装Mysql多实例作为数据备份服务器实现多主到一从多实例的备份
2024-01-13 19:12:27
ASP编程入门进阶(十):Global.asa文件
2008-07-12 07:05:00
JavaScript设计模式之原型模式分析【ES5与ES6】
2024-05-02 16:29:37
Python使用sax模块解析XML文件示例
2021-11-28 15:31:39
vue实现鼠标滑动展示tab栏切换
2023-07-02 16:38:05
![](https://img.aspxhome.com/file/2023/4/139744_0s.gif)
Python OpenCV视频截取并保存实现代码
2023-01-05 06:04:21
Python使用pandas导入csv文件内容的示例代码
2022-07-25 15:34:16
![](https://img.aspxhome.com/file/2023/7/110387_0s.png)
PyTorch使用GPU训练的两种方法实例
2023-09-21 08:11:40
![](https://img.aspxhome.com/file/2023/9/85309_0s.png)
教你利用python的matplotlib(pyplot)绘制折线图和柱状图
2022-02-25 17:30:49
![](https://img.aspxhome.com/file/2023/6/93626_0s.png)
python使用pygame框架实现推箱子游戏
2022-02-12 00:34:13
![](https://img.aspxhome.com/file/2023/6/105866_0s.jpg)
numpy.transpose()实现数组的转置例子
2021-11-14 13:24:55
Web2.0视觉风格进化论 之一
2007-11-03 19:58:00
![](https://img.aspxhome.com/file/UploadPic/up/2007110320250569.gif)
编写Python脚本抓取网络小说来制作自己的阅读器
2022-11-06 18:51:03
![](https://img.aspxhome.com/file/2023/7/99437_0s.png)