python上下文管理的使用場(chǎng)景實(shí)例講解
凡是要在代碼塊前后插入代碼的場(chǎng)景,這點(diǎn)和裝飾器類似。
資源管理類:申請(qǐng)和回收,包括打開文件、網(wǎng)絡(luò)連接、數(shù)據(jù)庫(kù)連接等;
權(quán)限驗(yàn)證。
2、實(shí)例>>> with Context():... raise Exception # 直接拋出異常...enter contextexit contextTraceback (most recent call last): File '/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py', line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File '<ipython-input-4-63ba5aff5acc>', line 2, in <module> raise ExceptionException
知識(shí)點(diǎn)擴(kuò)展:
python上下文管理器異常問(wèn)題解決方法
異常實(shí)例
如果我們需要對(duì)異常做特殊處理,就可以在這個(gè)方法中實(shí)現(xiàn)自定義邏輯。
之所以 with 能夠自動(dòng)關(guān)閉文件資源,就是因?yàn)閮?nèi)置的文件對(duì)象實(shí)現(xiàn)了上下文管理器協(xié)議,這個(gè)文件對(duì)象的 __enter__ 方法返回了文件句柄,并且在 __exit__ 中實(shí)現(xiàn)了文件資源的關(guān)閉,另外,當(dāng) with 語(yǔ)法塊內(nèi)有異常發(fā)生時(shí),會(huì)拋出異常給調(diào)用者。
class File: def __enter__(self): return file_obj def __exit__(self, exc_type, exc_value, exc_tb): # with 退出時(shí)釋放文件資源 file_obj.close() # 如果 with 內(nèi)有異常發(fā)生 拋出異常 if exc_type is not None: raise exception
在__exit__方法中處理異常實(shí)例擴(kuò)展:
class File(object): def __init__(self, file_name, method): self.file_obj = open(file_name, method) def __enter__(self): return self.file_obj def __exit__(self, type, value, traceback): print('Exception has been handled') self.file_obj.close() return True with File(’demo.txt’, ’w’) as opened_file: opened_file.undefined_function() # Output: Exception has been handled
到此這篇關(guān)于python上下文管理的使用場(chǎng)景實(shí)例講解的文章就介紹到這了,更多相關(guān)python上下文管理的使用場(chǎng)景內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 基于android studio的layout的xml文件的創(chuàng)建方式2. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題3. 詳解Android studio 動(dòng)態(tài)fragment的用法4. Android如何加載Base64編碼格式圖片5. 圖文詳解vue中proto文件的函數(shù)調(diào)用6. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)7. 什么是python的自省8. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟9. Vuex localStorage的具體使用10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備