Python之面向对象上下文管理协议

  析构函数:

 import time
class Open:
def __init__(self,filepath,mode='r',encode='utf-8'):
self.f=open(filepath,mode=mode,encoding=encode) def write(self):
pass def __getattr__(self, item):
return getattr(self.f,item) def __del__(self):
print('----->del')
self.f.close() f=Open('a.txt','w')
f1=f
del f print('=========>')

  上下文管理协议: 

 # with open('a.txt','r') as f:
# print('--=---->')
# print(f.read()) # with open('a.txt', 'r'):
# print('--=---->') #
class Foo:
def __enter__(self):
print('=======================》enter')
return 111111111111111 def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
print('exc_type',exc_type)
print('exc_val',exc_val)
print('exc_tb',exc_tb)
return True # with Foo(): #res=Foo().__enter__()
# pass with Foo() as obj: #res=Foo().__enter__() #obj=res
print('with foo的自代码块',obj)
raise NameError('名字没有定义')
print('************************************') print('')

 

 # import time
# class Open:
# def __init__(self,filepath,mode='r',encode='utf-8'):
# self.f=open(filepath,mode=mode,encoding=encode) # def write(self,line):
# self.f.write(line) # def __getattr__(self, item):
# return getattr(self.f,item) # def __del__(self):
# print('----->del')
# self.f.close() # def __enter__(self):
# return self.f
# def __exit__(self, exc_type, exc_val, exc_tb):
# self.f.close() # with Open('George'.txt','w') as f:
# f.write('Georgetest\n')
# f.write('Georgetest\n')
# f.write('Georgetest\n')
# f.write('Georgetest\n')
# f.write('Georgetest\n') class Open:
def __init__(self,filepath,mode,encode='utf-8'):
self.f=open(filepath,mode=mode,encoding=encode)
self.filepath=filepath
self.mode=mode
self.encoding=encode def write(self,line):
print('write')
self.f.write(line) def __getattr__(self, item):
return getattr(self.f,item) def __enter__(self):
return self def __exit__(self, exc_type, exc_val, exc_tb):
self.f.close()
return True with Open('aaaaa.txt','w') as write_file: #write_file=Open('aaaaa.txt','w')
write_file.write('123123123123123\n')
write_file.write('123123123123123\n')
print(sssssssssssssss)
write_file.write('123123123123123\n')
04-23 12:27