python with语句的工作原理
发布时间:2024-08-14 11:21:30

1、说明
(1)上下文管理对象必须有内置操作符__enter__和__exit__方法。
(2)将对象管理器返回到with句子中并分配变量时,将召回__enter__方法。
(3)执行嵌套句,即上述相关代码。
(4)如有异常信息,将回调__exit同时携带type的方法,value,三个traceback参数(通过syssceback).exc_info获得)
(5)正常执行完成后,召回__exit__方法。
2、实例
#exception.pyclassWithContextObject:
defmessage(self,args):
print(args)def__enter__(self):
print("executeentermethod..")returnselfdef__exit__(self,exc_type,exc_val,exc_tb):
ifexc_typeisNone:
print("executenormally...")else:
print("raiseexception...")returnFalsedeftest_with():
withWithContextObject()ascontext:
context.message("takemessage")if__name__='__main__':
test_with()>>>pythonexception.py以上是python with语句的工作做原理,希望对大家有所帮助。更多Python学习指导:python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
