一句话理解python 上下文管理器 with as

不念不忘少年蓝@ 2022-05-01 13:46 248阅读 0赞

上下文管理器:包含了__enter__和__exit__方法的一个类

举例:

  1. class LookingClass:
  2. def __enter__(self):
  3. import sys
  4. self.original_write = sys.stdout.write
  5. sys.stdout.write = self.reverse_write
  6. print('exc enter')
  7. return '通过as返回给 对象的值'
  8. def reverse_write(self,text):
  9. self.original_write(text[::-1])
  10. def __exit__(self,exc_type,exc_value,traceback):
  11. import sys
  12. print('exc __exit__')
  13. sys.stdout.write = self.original_write
  14. return True

执行实例:

  1. >>> with LookingClass() as tt:
  2. print('i love python')
  3. print('123456')
  4. __retne__ cxe
  5. nohtyp evol i
  6. 654321
  7. __tixe__ cxe
  8. >>> print(tt)
  9. 通过as返回给 对象的值

上下文管理器目的是为了取代大量使用try…finally…
ps:open()函数是继承了带有__enter__和__exit__方法的类(IOBase),所以可以直接用 with open()as f:

发表评论

表情:
评论列表 (有 0 条评论,248人围观)

还没有评论,来说两句吧...

相关阅读

    相关 理解yield

    简要理解:yield就是 return 返回一个值,并且记住这个返回的位置,下次迭代就从这个位置后开始。(可以理解为程序终止,之后下一次用next,程序修复好,冲这个位置继续执