笔记-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语句执行步骤如下所述:

  1. 上下文声明生成一个上下文管理器;
  2. 上下文管理器的__exit__()方法被加载以待后续使用;
  3. 上下文管理器的__enter__()方法被引用执行;
  4. 如果with语句完成,__enter__()的返回值被赋与;
  5. 执行suite套件;
  6. 上下文管理器的__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

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的更多相关文章

  1. 笔记-python操作mysql

    笔记-python操作mysql 1.      开始 1.1.    环境准备-mysql create database db_python; use db_python; create tabl ...

  2. 笔记-python tutorial-9.classes

    笔记-python tutorial-9.classes 1.      Classes 1.1.    scopes and namespaces namespace: A namespace is ...

  3. 笔记-python异常信息输出

    笔记-python异常信息输出 1.      异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...

  4. 笔记-python -asynio

    笔记-python -asynio 1.      简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...

  5. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

  6. MongoDB学习笔记:Python 操作MongoDB

    MongoDB学习笔记:Python 操作MongoDB   Pymongo 安装 安装pymongopip install pymongoPyMongo是驱动程序,使python程序能够使用Mong ...

  7. 机器学习实战笔记(Python实现)-08-线性回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  8. 机器学习实战笔记(Python实现)-05-支持向量机(SVM)

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  9. 机器学习实战笔记(Python实现)-04-Logistic回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  10. 机器学习实战笔记(Python实现)-03-朴素贝叶斯

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

随机推荐

  1. ajax提交 返回值为undefined

    easyui  form 表单提交成功,但是返回值为undefined,原因是返回值不是json格式,是字符串的格式,那么解决办法就是把其转化成json格式 示例: $(function () { / ...

  2. echarts渲染一个风向图

    今天给大家说一个用echarts渲染一个风向图,这里图上其实有三个要素,风向,风级和能见度,主要还是讲讲代码里面的坑 1.风向图标方向修改以及设置 var ownData = echarts.util ...

  3. c++ 处理utf-8字符串

    c++的字符串中的每一个元素都是一个字节.所以在装入utf8字符串的时候,其实是按照一定的规则编码的. 字符的8位中 如果0开头 则自己就是一个单位. 1字节 0xxxxxxx  2字节 110xxx ...

  4. SpringCloud的学习记录(5)

    这一章节讲如何使用ribbon和hystrix. 在我们生成的Demo项目上右键点击New->Module->spring Initializr, 然后next, 填写Group和Arti ...

  5. UIWindow及程序启动的过程

    1.   UIWindow才有自发显示的功能, 一个程序之所以能显示东西,是因为有window !//  [self.window makeKeyAndVisible]; 2.   任何view的显示 ...

  6. ZIP文件流压缩和解压

    前面写了一篇文章 "ZIP文件压缩和解压", 介绍了" SharpZipLib.Zip " 的使用, 最近的项目中,在使用的过程中, 遇到一些问题. 比如, 现 ...

  7. Azure 5 月新公布(二)

    Azure 5 月新发布(二):CDN 图片处理功能, CDN Restful API, 新版 CDN 管理门户, 计量名称变更延期  Azure CDN 图片处理功能开放公共预览版 Azure CD ...

  8. graphql 项目搭建(二)

    一.Express基本框架 1.新建一个文件夹gql-server vscode 打开项目,在终端下输入yarn init -y 生成package.json 包(如果没安装yarn ,npm也一样, ...

  9. robotframework实战一

    1.环境 1.Robotframework 安装环境,见以下帖子,只要保证python安装成功,安装了python的pip,就可以使用pip一路安装下去了.以下帖子也有基础的操作,帖子路径 http: ...

  10. jade文档声明和头尾标签

    作为一个页面,首先需要一个doctype的声明,它位于文档最上面的位置,放置html标签以前,用来告知浏览器当前这个页面用哪种html,或者xml的规范并解析页面   doctype html htm ...