笔记-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-朴素贝叶斯
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
随机推荐
- canvas绘制圆环
- Design Pattern ->Bridge
Layering & Contract Philosophy With additional indirection. class CWindowImp { public: virtual v ...
- css3实现iPhone滑动解锁
该效果的主要实现思路是给文字添加渐变的背景,然后对背景进行裁剪,按文字裁剪(目前只有webkit内核浏览器支持该属性),最后给背景添加动画,即改变背景的位置,背景动画效果如下(GIF录制时有卡顿,代码 ...
- Android @1x,@2x,@3x 资源文件自动分包工具
version 1.2 1.修改不用输入扩展名 2.输出路径可选.默认会在输入路径下建文件夹 前沿: 现在开发中ios,android会使用一套图,但是ui设计师给的图命名是以@1x,@2x,@3x这 ...
- Android - 通过真实案例学习解内存泄漏问题,最终发现Android原生Bug
作为一个Android新手小白,刚到新公司,最近的工作就是在学习解各类Bug.转型之初,面临各种新知识,会有压力,但是学习的过程是快乐的. 上周刚遇上一类bug,就是应用的内存泄漏问题.最终通过前辈的 ...
- python列表生成式、列表推导式
运用列表生成式,可以快速生成list,可以通过一个list推导出另一个list,而代码却十分简洁. 格式 [x for x in 内容] [x for x in 内容 if 条件] 1:要把生成的元素 ...
- nginx启动时报错
nginx启动时报错 原因:nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed /var/cache/ngin ...
- Azure本月最新活动,速度Mark!
桃花夭夭,渌水盈盈,就这样四月的脚步迫不及待地来了.为了帮助您能在第一时间了解 Azure 最新的活动,我们推出每月活动合集,你准备好了吗,一起来看吧! 立即访问http://market.azure ...
- php的yii框架开发总结3
利用yii里面的gii工具可以很容易的自动创建数据表相应的的CURD操作的基于MVC的文件: 首先,打开:自己网站/protected/config/main.php文件 'modules'=> ...
- Properties的使用以及配置文件值的获取
一.项目的部署如下,现在要获取SystemGlobals.properties中的值 二.代码如下: package com.util; import java.io.IOException; imp ...