1、上下文管理的使用場景
凡是要在代碼塊前后插入代碼的場景,這點(diǎn)和裝飾器類似。
資源管理類:申請(qǐng)和回收,包括打開文件、網(wǎng)絡(luò)連接、數(shù)據(jù)庫連接等;
權(quán)限驗(yàn)證。
2、實(shí)例
>>> with Context():
... raise Exception # 直接拋出異常
...
enter context
exit context
Traceback (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 Exception
Exception
知識(shí)點(diǎn)擴(kuò)展:
python上下文管理器異常問題解決方法
異常實(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 語法塊內(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 詳解python with 上下文管理器
- Python實(shí)現(xiàn)上下文管理器的方法
- Python Flask上下文管理機(jī)制實(shí)例解析
- python中with語句結(jié)合上下文管理器操作詳解
- python 上下文管理器及自定義原理解析