python上下文管理的使用場景實(shí)例講解
凡是要在代碼塊前后插入代碼的場景,這點(diǎn)和裝飾器類似。
資源管理類:申請和回收,包括打開文件、網(wǎng)絡(luò)連接、數(shù)據(jù)庫連接等;
權(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上下文管理器異常問題解決方法
異常實(shí)例
如果我們需要對異常做特殊處理,就可以在這個(gè)方法中實(shí)現(xiàn)自定義邏輯。
之所以 with 能夠自動(dòng)關(guān)閉文件資源,就是因?yàn)閮?nèi)置的文件對象實(shí)現(xiàn)了上下文管理器協(xié)議,這個(gè)文件對象的 __enter__ 方法返回了文件句柄,并且在 __exit__ 中實(shí)現(xiàn)了文件資源的關(guān)閉,另外,當(dāng) with 語法塊內(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上下文管理的使用場景實(shí)例講解的文章就介紹到這了,更多相關(guān)python上下文管理的使用場景內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用css實(shí)現(xiàn)全兼容tooltip提示框2. div的offsetLeft與style.left區(qū)別3. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)4. Vue3使用JSX的方法實(shí)例(筆記自用)5. JavaScript數(shù)據(jù)類型對函數(shù)式編程的影響示例解析6. 詳解CSS偽元素的妙用單標(biāo)簽之美7. CSS代碼檢查工具stylelint的使用方法詳解8. 利用CSS3新特性創(chuàng)建透明邊框三角9. vue實(shí)現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細(xì)教程10. 不要在HTML中濫用div
