python上下文管理的使用場(chǎng)景實(shí)例講解
凡是要在代碼塊前后插入代碼的場(chǎng)景,這點(diǎn)和裝飾器類似。
資源管理類:申請(qǐng)和回收,包括打開(kāi)文件、網(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. PHP設(shè)計(jì)模式中工廠模式深入詳解2. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明3. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)4. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析5. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過(guò)程(親測(cè)可用)6. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法7. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息8. 解決AJAX返回狀態(tài)200沒(méi)有調(diào)用success的問(wèn)題9. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向10. CSS hack用法案例詳解
