__enter__
方法初始化,然后在__exit__
中做善后以及处理异常。所以使用with处理的对象必须有__enter__()
和__exit__()
这两个方法。# 打开1.txt文件,并打印输出文件内容
with open(‘1.txt‘, ‘r‘, encoding="utf-8") as f:
print(f.read())
看这段代码是不是似曾相识呢?是就对了!
with expression [as target]:
with_body
参数说明:
expression
:是一个需要执行的表达式;
target
:是一个变量或者元组,存储的是expression表达式执行返回的结果,[]表示该参数为可选参数。
expression
表达式,如果表达式含有计算、类初始化等内容,会优先执行。__enter()__
方法中的代码__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资源
test()
方法。testwith
类是我们用来测试with...as...
语法的类,用来给testclass类进行善后(释放资源等)。
欢迎各位老铁一键三连,本号后续会不断更新树莓派、人工智能、STM32、ROS小车相关文章和知识。
大家对感兴趣的知识点可以在文章下面留言,我可以优先帮大家讲解哦
原创不易,转载请说明出处。
原文:https://www.cnblogs.com/ChuanYangRiver/p/15308236.html