码迷,mamicode.com
首页 > 其他好文 > 详细

上下文管理器

时间:2019-08-06 22:47:17      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:__enter__   init   with   efi   val   nbsp   define   object   obj   

 
 1 class Open:
 2     def __init__(self,name):
 3         self.name = name
 4 
 5     def __enter__(self):
 6         print("触发enter")
 7 
 8     def __exit__(self, exc_type, exc_val, exc_tb):
 9         print(exc_tb,\n,exc_val,\n,exc_type)  #接收异常的三个参数
10         print("退出exit")
11 
12 with Open(a.txt) as f:
13     print("===========")
14     print("===========")
15     # print(dfasdklf)  
16     print("===========")
17     ‘‘‘
18     输出:
19         触发enter
20         ===========
21         ===========
22         ===========
23         None 
24          None 
25          None
26         退出exit
27     ‘‘‘

下面,让程序产生异常:

 1 class Open:
 2     def __init__(self,name):
 3         self.name = name
 4 
 5     def __enter__(self):
 6         print("触发enter")
 7 
 8     def __exit__(self, exc_type, exc_val, exc_tb):
 9         print(exc_tb,\n,exc_val,\n,exc_type)  #接收异常的三个参数
10         print("退出exit")
11 
12 with Open(a.txt) as f:
13     print("===========")
14     print("===========")
15     print(dfasdklf)
16     print("===========")
17     ‘‘‘
18     输出:
19         触发enter
20         ===========
21         ===========   #总共两个,说明出现异常立即退出
22         <traceback object at 0x0000014E7651D0C8> 
23          name ‘dfasdklf‘ is not defined 
24          <class ‘NameError‘>
25         退出exit
26     ‘‘‘

 自定义用于打开文件的上下文管理器:

 1 class MyOpenClass:
 2     def __init__(self,name,mode):
 3         self.name= name
 4         self.mode= mode
 5     
 6     def __enter__(self):
 7         print("进入上下文管理器")
 8         if self.mode == r:
 9             self.f = open(self.name,self.mode)
10         else:
11             self.f= open(self.name,self.mode)
12         return self #重点,要将self, 它返回的就是as 后面的那个
13     
14     def __exit__(self, exc_type, exc_val, exc_tb):
15         self.f.close()
16         print("退出上下文管理器")
17     def read(self):
18         return self.f.read()
19     def write(self,s):
20         self.f.write(s)
21 if __name__ =="__main__":
22     with MyOpenClass("d:/test.txt",r) as f1,MyOpenClass("d:/test02.txt",w) as f2:
23         txt = f1.read() #从f1中读
24         print(txt)
25         f2.write(txt)  # 写到f2中去

 

上下文管理器

标签:__enter__   init   with   efi   val   nbsp   define   object   obj   

原文地址:https://www.cnblogs.com/zach0812/p/11312278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!