您的位置:首页 > 编程语言 > Python开发

python上下文管理的使用场景实例讲解

2021-03-05 04:06 1076 查看

1、上下文管理的使用场景

凡是要在代码块前后插入代码的场景,这点和装饰器类似。

资源管理类:申请和回收,包括打开文件、网络连接、数据库连接等;

权限验证。

2、实例

>>> 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

知识点扩展:

python上下文管理器异常问题解决方法

异常实例

如果我们需要对异常做特殊处理,就可以在这个方法中实现自定义逻辑。

之所以 with 能够自动关闭文件资源,就是因为内置的文件对象实现了上下文管理器协议,这个文件对象的 __enter__ 方法返回了文件句柄,并且在 __exit__ 中实现了文件资源的关闭,另外,当 with 语法块内有异常发生时,会抛出异常给调用者。

class File:
def __enter__(self):
return file_obj
def __exit__(self, exc_type, exc_value, exc_tb):
# with 退出时释放文件资源
file_obj.close()
# 如果 with 内有异常发生 抛出异常
if exc_type is not None:
raise exception

在__exit__方法中处理异常实例扩展:

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

到此这篇关于python上下文管理的使用场景实例讲解的文章就介绍到这了,更多相关python上下文管理的使用场景内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 上下文管理