首页 / 知识

pythonwith语句的工作原理

2023-11-12 12:54:00

pythonwith语句的工作原理

1、说明

(1)上下文管理器对象必须有内置操作符__enter__和__exit__方法。

(2)在with句子中返回对象管理器并分配变量时,将召回__enter__方法。

(3)执行嵌套句,即上述相关代码。

(4)如果出现异常信息,将回调__exit__的方法,同时携带type,value,traceback三个参数(通过sys.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

以上就是pythonwith语句的工作原理,希望对大家有所帮助。更多Python学习教程请关注我们

培训异常代码信息语句

最新内容

相关内容

热门文章

推荐文章

标签云

猜你喜欢