笔记-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. 使用js来执行全屏

    当用户按下F11事件,浏览器为触发自身全屏功能,这个过程我们一般是不可控制的,即使是监听了F11的键盘事件,退出全屏的时候,我们也捕捉不到退出全屏触发的事件.所以,我们就用程序自己去实现F11的功能, ...

  2. 一步步理解typedef

    1.如何用C语言实现一个函数,传递两个整形数,返回两个数的和? #include<stdio.h> int add(int a,int b) { return a+b; } void ma ...

  3. 【MATLAB】产生FPGA中ROM需要的余弦表

    产生的二进制数为带符号二进制数,最高位是符号位. function [ DATA ] = cos_gen( Num_addr,Num_out ) % 用来产生ROM需要的余弦表,输出为有符号二进制数 ...

  4. Quartz .Net(定时框架):

    Quartz .Net(定时框架): 基本说明: 说明:Quartz .Net 是一个从 Java 版的 Quartz 移植过来定时任务框架,可以实现异常灵活的定 时任务 用法: 安装 Quartz ...

  5. UDoc(云平台企业应用级 文档管理产品)

    类型: 定制服务 软件包: integrated industry solution collateral 联系服务商 产品详情 解决方案 概要 为企业提供基于云平台企业应用级文档管理产品,尽可能最大 ...

  6. lrzsz的使用

    可以方便的在本地PC机和远程服务器之间传输文件. 1.下载 直接在centos上执行命令yum -y install lrzsz 2.上传文件 rz // 上传文件,执行命令rz,会跳出文件选择窗口, ...

  7. Linux学习_按时间顺序解压多个文件,搜索文件中的内容

    ls的结果按时间数据先排序,再取末尾5个文件,再调用tar命令 ls -1 | sort -u | tail -5 |xargs -n1 tar xzvf 利用grep命令从文件中搜索. grep - ...

  8. Node.js-sublime text3 配置node.js(ERROR: The process "node.exe" not found.)

    默认已经安装好sublime.node和npm 1.sublime的node.js插件下载 由于在package control上经常下载失败,所以这里直接从GitHub上进行下载! GitHub下载 ...

  9. java日期时间Date类

    java.util包提供了Date类来封装当前的日期和时间. Date类提供两个构造函数来实例化Date对象. 第一个构造函数使用当前日期和时间来初始化对象. Date( ) 第二个构造函数接收一个参 ...

  10. Altium_Designer-怎么将“原理图的更改”更新到“pcb图”?

    打开原理图,直击菜单栏>>Design,选择第一项,>>Update PCB Document...在弹出的对话框里面选择执行更改即可将原理图更新到工程下面对应的PCB.也可以 ...