一句话理解python 上下文管理器 with as
上下文管理器:包含了__enter__和__exit__方法的一个类
举例:
class LookingClass:
def __enter__(self):
import sys
self.original_write = sys.stdout.write
sys.stdout.write = self.reverse_write
print('exc enter')
return '通过as返回给 对象的值'
def reverse_write(self,text):
self.original_write(text[::-1])
def __exit__(self,exc_type,exc_value,traceback):
import sys
print('exc __exit__')
sys.stdout.write = self.original_write
return True
执行实例:
>>> with LookingClass() as tt:
print('i love python')
print('123456')
__retne__ cxe
nohtyp evol i
654321
__tixe__ cxe
>>> print(tt)
通过as返回给 对象的值
上下文管理器目的是为了取代大量使用try…finally…
ps:open()函数是继承了带有__enter__和__exit__方法的类(IOBase),所以可以直接用 with open()as f:
还没有评论,来说两句吧...