Python之面向对象上下文管理协议
析构函数:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 import time 2 class Open: 3 def __init__(self,filepath,mode='r',encode='utf-8'): 4 self.f=open(filepath,mode=mode,encoding=encode) 5 6 def write(self): 7 pass 8 9 def __getattr__(self, item): 10 return getattr(self.f,item) 11 12 def __del__(self): 13 print('----->del') 14 self.f.close() 15 16 f=Open('a.txt','w') 17 f1=f 18 del f 19 20 print('=========>')
上下文管理协议:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # with open('a.txt','r') as f: 2 # print('--=---->') 3 # print(f.read()) 4 5 # with open('a.txt', 'r'): 6 # print('--=---->') 7 8 9 # 10 class Foo: 11 def __enter__(self): 12 print('=======================》enter') 13 return 111111111111111 14 15 def __exit__(self, exc_type, exc_val, exc_tb): 16 print('exit') 17 print('exc_type',exc_type) 18 print('exc_val',exc_val) 19 print('exc_tb',exc_tb) 20 return True 21 22 23 # with Foo(): #res=Foo().__enter__() 24 # pass 25 26 with Foo() as obj: #res=Foo().__enter__() #obj=res 27 print('with foo的自代码块',obj) 28 raise NameError('名字没有定义') 29 print('************************************') 30 31 print('1111111111111111111111111111111111111111')
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # import time 2 # class Open: 3 # def __init__(self,filepath,mode='r',encode='utf-8'): 4 # self.f=open(filepath,mode=mode,encoding=encode) 5 6 # def write(self,line): 7 # self.f.write(line) 8 9 10 # def __getattr__(self, item): 11 # return getattr(self.f,item) 12 13 # def __del__(self): 14 # print('----->del') 15 # self.f.close() 16 17 # def __enter__(self): 18 # return self.f 19 # def __exit__(self, exc_type, exc_val, exc_tb): 20 # self.f.close() 21 22 23 # with Open('George'.txt','w') as f: 24 # f.write('Georgetest\n') 25 # f.write('Georgetest\n') 26 # f.write('Georgetest\n') 27 # f.write('Georgetest\n') 28 # f.write('Georgetest\n') 29 30 31 class Open: 32 def __init__(self,filepath,mode,encode='utf-8'): 33 self.f=open(filepath,mode=mode,encoding=encode) 34 self.filepath=filepath 35 self.mode=mode 36 self.encoding=encode 37 38 def write(self,line): 39 print('write') 40 self.f.write(line) 41 42 def __getattr__(self, item): 43 return getattr(self.f,item) 44 45 def __enter__(self): 46 return self 47 48 def __exit__(self, exc_type, exc_val, exc_tb): 49 self.f.close() 50 return True 51 52 with Open('aaaaa.txt','w') as write_file: #write_file=Open('aaaaa.txt','w') 53 write_file.write('123123123123123\n') 54 write_file.write('123123123123123\n') 55 print(sssssssssssssss) 56 write_file.write('123123123123123\n')