__enter__和__exit__的用法

Posted study_python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了__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__的用法的主要内容,如果未能解决你的问题,请参考以下文章

Python中with用法详解

python3with的用法

python中的with用法

如何用python 中with 用法

python中with用法理解

python with as的用法