Python中with...as...的使用方法
作者:折腾一哥 时间:2021-10-01 16:58:07
简介:
with
是从Python2.5
引入的一个新的语法,它是一种上下文管理协议,目的在于从流程图中把 try,except 和finally 关键字和资源分配释放相关代码统统去掉,简化try….except….finlally
的处理流程with
通过__enter__
方法初始化,然后在__exit__
中做善后以及处理异常。所以使用with
处理的对象必须有__enter__()
和__exit__()
这两个方法。with
语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。
举例如下:
# 打开1.txt文件,并打印输出文件内容
with open('1.txt', 'r', encoding="utf-8") as f:
print(f.read())
看这段代码是不是似曾相识呢?是就对了!
一、With...as语句的基本语法格式:
with expression [as target]:
with_body
参数说明:
expression:
是一个需要执行的表达式;target:
是一个变量或者元组,存储的是expression
表达式执行返回的结果,[]表示该参数为可选参数。
二、With...as语法的执行流程
首先运行
expression
表达式,如果表达式含有计算、类初始化等内容,会优先执行。运行
__enter()__
方法中的代码运行
with_body
中的代码运行
__exit()__
方法中的代码进行善后,比如释放资源,处理错误等。
三、实例验证
#!/usr/bin/python3
# -*- coding: utf-8 -*-
""" with...as...语法测试 """
__author__ = "River.Yang"
__date__ = "2021/9/5"
__version__ = "1.1.0"
class testclass(object):
def test(self):
print("test123")
print("")
class testwith(object):
def __init__(self):
print("创建testwith类")
print("")
def __enter__(self):
print("进入with...as..前")
print("创建testclass实体")
print("")
tt = testclass()
return tt
def __exit__(self, exc_type, exc_val, exc_tb):
print("退出with...as...")
print("释放testclass资源")
print("")
if __name__ == '__main__':
with testwith() as t:
print("with...as...程序内容")
print("with_body")
t.test()
四、程序运行结果
创建testwith类
进入with...as..前
创建testclass实体
with...as...程序内容
with_body
test123
退出with...as...
释放testclass资源
五、代码解析
这段代码一共创建了2个类,第一个testclass
类是功能类,用于存放定义我们需要的所有功能比如这里的test()方法。testwith
类是我们用来测试with...as...
语法的类,用来给testclass
类进行善后(释放资源等)。
程序执行流程:
来源:https://www.cnblogs.com/ChuanYangRiver/p/15308236.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django修改app名称和数据表迁移方案实现
python基础之函数
![](https://img.aspxhome.com/file/2023/8/79618_0s.png)
SQL参数化查询的另一个理由 命中执行计划
使用PyTorch实现随机搜索策略
![](https://img.aspxhome.com/file/2023/4/75864_0s.png)
防采集,几种觉得有用的防采集方法
Go slice切片使用示例详解
![](https://img.aspxhome.com/file/2023/1/87611_0s.jpg)
asp当中判断函数一览
对python中list的拷贝与numpy的array的拷贝详解
![](https://img.aspxhome.com/file/2023/2/68952_0s.jpg)
胜过语言的图形符号
![](https://img.aspxhome.com/file/UploadPic/20095/6/2009-05-03_001747-150x137-79s.png)
网友分享:Oracle数据库开发技术经验浅谈
Python中 join() 函数的使用示例讲解
打造设计你自己的字体 Ⅲ
![](https://img.aspxhome.com/file/UploadPic/20083/14/200831475626244s.gif)
jQuery初学:find()方法及children方法的区别分析
![](https://img.aspxhome.com/file/UploadPic/20112/5/20112511038177s.png)
Python使用Matplotlib绘制三维散点图详解流程
![](https://img.aspxhome.com/file/2023/5/69445_0s.png)
如何使用Iframe实现本页提交?
Python环境下搭建属于自己的pip源的教程
Opencv实现二维直方图的计算及绘制
![](https://img.aspxhome.com/file/2023/6/59646_0s.jpg)
python之线程通过信号pyqtSignal刷新ui的方法
![](https://img.aspxhome.com/file/2023/5/70165_0s.jpg)