笔记-python-statement-with
笔记-python-statement-with
1. with语句
1.1. 基础使用案例
在开发时,经常使用with语句来打开文件:
with open(‘a.txt’,’a+’,encoding=’utf-8’) as fi:
data = fi.read()
从效果上而言上一句话等效于下文
try:
f = open('xxx')
except:
print 'fail to open'
exit(-1)
try:
do something
except:
do something
finally:
f.close()
1.2. with原理
with其实等效于try…except…finally语句,
with语句执行步骤如下所述:
- 上下文声明生成一个上下文管理器;
- 上下文管理器的__exit__()方法被加载以待后续使用;
- 上下文管理器的__enter__()方法被引用执行;
- 如果with语句完成,__enter__()的返回值被赋与;
- 执行suite套件;
- 上下文管理器的__exit__()方法被引用执行。如果suite执行发生异常,异常的type,value,traceback作为参数传给__exit__(),否则传送三个none。
如果suite以异常结束,而且__exit__()的返回值是false,抛出异常;如果__exit__()返回值是true,异常被处理,会执行接下来的语句。
with A() as a, B() as b:
suite
等效于:
with A() as a:
with B() as b:
suite
1.3. context manager
文档位于https://docs.python.org/3/reference/datamodel.html#special-method-names
A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.
Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.
For more information on context managers, see Context Manager Types.
核心是两个方法:
object.__enter__(self)
Enter the runtime context related to this object. The withstatement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.
简单来说,enter()的返回值会绑定到as分钟所声明的对象上。
object.__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.
If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.
Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.
1.4. 参考文档
https://docs.python.org/3/reference/compound_stmts.html#the-with-statement
https://docs.python.org/3/reference/datamodel.html#special-method-names
笔记-python-statement-with的更多相关文章
- 笔记-python操作mysql
笔记-python操作mysql 1. 开始 1.1. 环境准备-mysql create database db_python; use db_python; create tabl ...
- 笔记-python tutorial-9.classes
笔记-python tutorial-9.classes 1. Classes 1.1. scopes and namespaces namespace: A namespace is ...
- 笔记-python异常信息输出
笔记-python异常信息输出 1. 异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...
- 笔记-python -asynio
笔记-python -asynio 1. 简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...
- 笔记-python lib-pymongo
笔记-python lib-pymongo 1. 开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...
- MongoDB学习笔记:Python 操作MongoDB
MongoDB学习笔记:Python 操作MongoDB Pymongo 安装 安装pymongopip install pymongoPyMongo是驱动程序,使python程序能够使用Mong ...
- 机器学习实战笔记(Python实现)-08-线性回归
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
- 机器学习实战笔记(Python实现)-05-支持向量机(SVM)
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
- 机器学习实战笔记(Python实现)-04-Logistic回归
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
- 机器学习实战笔记(Python实现)-03-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
随机推荐
- scss牛刀小试:解决css中适配浏览器前缀问题
在css中为适配浏览器,新特性总加 -webkit,-o, -moz 来适配浏览器,写的烦心,看着也臃肿,让css可读性降低,下面以阴影为例,如何使用scss让我们的css看起来更简洁. 本人使用的I ...
- 数据批量删除_从页面js到后台数据库
LayUI 批量选择的 ,然后操作 batchdel: function () { var checkStatus = table.checkStatus('LAY-gridview') , ch ...
- DOM对象和js对象以及jQuery对象的区别
DOM对象和js对象以及jQuery对象的区别 DOM对象和js对象以及jQuery对象的区别 一.DOM对象 文档对象模型简称DOM,是W3C组织推荐的处理可扩展置标语言的标准编程接口. DOM实际 ...
- SaberSama【css总结】
为什么要转过来呢? 因为我觉到,同样是一个初学者,应该互相学习,交流. css:Cascading Style Sheets 层叠样式表 CSS引入方式: 1.内嵌: <p style=&quo ...
- 运行在 Android 系统上的完整 Linux -- Termux
Termux 可以在安卓系统上搭建一个完整的linux 环境,类似于 cygwin 并非linux 虚拟机,整个安装包只有 几百KB 刚开始觉得这东西的命令行很难用,看了官方介绍后才发现它原来有许多 ...
- windows如何关闭指定端口
关闭windows中被占用的端口,比如我们常见的8080端口被占用了 1.查找端口的PID netstat -aon|findstr "8080" 如图 PID为3888 2.关闭 ...
- mysql索引长度
http://blog.csdn.net/qsc0624/article/details/51335632 大家应该知道InnoDB单列索引长度不能超过767bytes,联合索引还有一个限制是长度不能 ...
- jenkins 执行shell命令出错command not found 和No such file or directory
[root@localhost usr]# sh test.sh command not found -bash: cd: usr: No such file or directory 这里碰到了一个 ...
- 2018年第九届蓝桥杯【C++省赛B组】第二题 明码
汉字的字形存在于字库中,即便在今天,16点阵的字库也仍然使用广泛.16点阵的字库把每个汉字看成是16x16个像素信息.并把这些信息记录在字节中. 一个字节可以存储8位信息,用32个字节就可以存一个汉字 ...
- 【洛谷P1948】[USACO08JAN]电话线
电话线 题目链接:https://www.luogu.org/problemnew/show/P1948 二分答案+最短路 我们要求一条1~n的路径,使其中的第k+1大的数最小. 二分第k+1大的数的 ...