pythonwith語句的工作原理
1、說明
(1)上下文管理器對(duì)象必須有內(nèi)置操作符__enter__和__exit__方法。
(2)在with句子中返回對(duì)象管理器并分配變量時(shí),將召回__enter__方法。
(3)執(zhí)行嵌套句,即上述相關(guān)代碼。
(4)如果出現(xiàn)異常信息,將回調(diào)__exit__的方法,同時(shí)攜帶type,value,traceback三個(gè)參數(shù)(通過sys.exc_info獲得)
(5)在正常執(zhí)行完成后,還召回__exit__的方法。
2、實(shí)例
#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語句的工作原理,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)教程請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。