笔记-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-朴素贝叶斯
		
--------------------------------------------------------------------------------------- 本系列文章为<机器 ...
 
随机推荐
- Android 设置软键盘搜索键以及监听搜索键点击事件
			
如图所示,有时候为了布局美观,在搜索时没有搜索按钮,而是调用软件盘上的按钮.调用的实现只需要在XML在输入框中加入android:imeOptions="actionSearch" ...
 - Arm启动流程解析
			
谈到arm的启动流程不得不说的是bootloader,但是我这篇文章主要来谈谈arm启动流程的,所以bootloader只是跟大家简介一下就ok.这篇文章我会谈到以下内容: 1.bootloader简 ...
 - 西门子 SINAMICS S120 Web server 用户名和默认密码
			
sinamics web server可以通过浏览器查看驱动器故障等信息,是一个比较方便的辅助工具. 1. 一般用户 SINAMICS 密码 无 2. 管理员 Administrator 密码 Adm ...
 - HTML入门1—HTML基础学习
			
html文档结构 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> < ...
 - CRUD全栈式编程架构之更精简的设计
			
精简的程度 ViewModel精简 服务精简 控制器精简 Index.cshmtl精简 AddOrEdit.cshtml精简 效果:最精简的情况下,只需要写Entity这一个数据库实体然后加上一些简单 ...
 - 常用mysql系统参数参考
			
http://aaronsa.blog.51cto.com/5157083/1741481
 - 【转】Xcode真机测试could not find developer disk image解决方法
			
在使用Xcode进行真机调试的时候,有时根据真机的系统不同,会出现could not find developer disk image 错误,这是由于真机系统过高或者过低,Xcode中没有匹配的配置 ...
 - c#转载的
			
C#做项目时的一些经验分享 1.对于公用的类型定义,要单独抽取出来,放到单独的DLL中. 2.通过大量定义interface接口,来提高模块化程度,不同功能之间通过实现接口来面向接口编程. 3.如果项 ...
 - centos7安装python3和ipython
			
CentOS7下默认系统自带python2.X的版本,这个版本被系统很多程序所依赖,所以不建议删除,如果使用最新的Python3那么我们知道编译安装源码包和系统默认包之间是没有任何影响的,所以可以安装 ...
 - Win10预览版激活信息
			
微软在10月2日零点正式公开了Win10预览版的下载地址,这个时间大家应该逐步开始安装工作了,因此提出下面两个问题的用户特别多,IT之家再稍作告知一下.1.Win10预览版安装密钥是什么?答:NKJF ...