-
Python中with...as...的用法详解
简介
- 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
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
数据库审计与智能监控:从日志分析到异
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比