首页 > 编程技术 > python

Python中with...as...的使用方法

发布时间:2021-9-18 16:00

简介:

举例如下:

# 打开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语法的执行流程

  1. 首先运行expression表达式,如果表达式含有计算、类初始化等内容,会优先执行。
  2. 运行__enter()__方法中的代码
  3. 运行with_body中的代码
  4. 运行__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类进行善后(释放资源等)。

程序执行流程:


到此这篇关于Pythonwith...as...的用法详解的文章就介绍到这了,更多相关Pythonwith...as...的用法内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: