首页 > 代码库 > __enter__和__exit__的用法

__enter__和__exit__的用法

#__enter__与__exit__是成对出现的,一般是在进行with obj时才会触发它们

class Open:
def __init__(self,filepath,mode=‘r‘,encode=‘utf-8‘):
self.f=open(filepath,mode=mode,encoding=encode)
# self.filepath =filepath
# self.mode =mode
# self.encoding =encode
def __getattr__(self, item):
return getattr(self.f,item)
def __enter__(self):
return self #如果是self.f,则在f.write(),就不会执行__getattr__方法

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

def __del__(self):
print(‘-->‘)
self.f.close()

#f =Open(‘a.txt‘,‘w‘)
with Open(‘a‘,‘w‘) as f:
print(f)
f.write(‘aaaaa\n‘) #f.write(item),因为对象f没有write()方法,就执行__getattr__方法
#即getattr(f.x,write)(item)
f.write(‘bbbb‘)

__enter__和__exit__的用法