编程语言
首页 > 编程语言> > 关于python中with语句的粗浅认识

关于python中with语句的粗浅认识

作者:互联网

上下文管理管理器:资源使用完成的释放很重要,python中使用上下文管理器来自动分配并释放资源。with语句操作对象就为一个上下文管理器对象。

基于类的上下文管理器的:

 1 class FileType:
 2     """
 3     使用类创建上下文管理器时必须包含__enter__()和__exit__()方法
 4     """
 5     def __init__(self, name, mode):
 6         self.name = name
 7         self.mode = mode
 8         self.file = None
 9 
10     def __enter__(self):
11         """
12         获取要操作的资源并且返回
13         :return:返回需要被管理的资源
14         """
15         self.file = open(self.name,self.mode)
16         return self.file
17 
18     def __exit__(self, exc_type, exc_val, exc_tb):
19         """
20         对资源的释放或者清理操作放在此方法里面
21         :param exc_type:异常类型
22         :param exc_val:异常值
23         :param exc_tb:异常错误栈信息
24         :return:当返回值为True时,表示告诉python解释器异常已经捕获无需再抛出异常
25         """
26         if exc_type:
27             print(f'exc_type: {exc_type}')
28         if self.file:
29             self.file.close()
View Code

with语句执行上下文管理器:

1 file_manager = FileType("text.txt", "w")
2 # 使用with执行这个文件上下文管理器
3 with file_manager as f:
4     f.write("this is my test.")

基于生成器的上下文管理器:

 1 from contextlib import contextmanager
 2 
 3 
 4 @contextmanager
 5 def file_manager(name, mode):
 6     try:
 7         f = open(name, mode)
 8         yield f
 9     finally:
10         f.close()
11 
12 
13 with file_manager('test.txt', 'w') as f:
14     f.write('hello world')

总结:

 

标签:语句,__,粗浅,管理器,exc,python,self,file,上下文
来源: https://www.cnblogs.com/BinZhou0901/p/14771804.html