python上下文管理的使用场景

Python (150) 2023-07-01 01:08:26

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

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

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

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

权限验证。

2、实例

>>>withContext():
...raiseException#直接抛出异常
...
entercontext
exitcontext
Traceback(mostrecentcalllast):
File"/usr/local/python3/lib/python3.6/site-packages/IPython/core/interactiveshell.py",line2862,inrun_code
exec(code_obj,self.user_global_ns,self.user_ns)
File"<ipython-input-4-63ba5aff5acc>",line2,in<module>
raiseException
Exception

以上就是python上下文管理的使用场景,希望能对大家有所帮助。更多Python学习指路:python基础教程

THE END

发表回复