Python积木之with
简而言之,with 语句是典型的程序块 “try catch finally”的一种模式抽取。python的作者在PEP343中写道
“ This PEP adds a new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements.”
这是Python追求语言简化做出的一种语法糖。
with 可以作用于类的某个方法,但是这个类必须实现__enter__和 __exit__两个方法。调用类的某个方法时,首先会调用__enter__方法,再调用方法本身,最后调用__exit__方法。
例如下面代码:
with file(r'D:\a.txt','r') as f :
print f.read()
这样,我们实现了读取a.txt所有内容。读取后又关闭了文件。
我们可以查看file方法所在的__builtin_模块,你可以搜索对应file类到__enter__和__exit__的方法(这个例子不好,因为file是c实现的,这里只有壳,但能帮助你明白是什么意思)
下面出自python的官方文档,详细说明了with的用法。with还支持嵌套。
with_stmt ::= "with" with_item ("," with_item)* ":" suite
with_item ::= expression ["as" target]
The context expression (the expression given in the with_item) is evaluated to obtain a context manager.
The context manager’s __exit__() is loaded for later use.
The context manager’s __enter__() method is invoked.
If a target was included in the with statement, the return value from __enter__() is assigned to it.
Note
The with statement guarantees that if the __enter__() method returns without an error, then __exit__() will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 6 below.
The suite is executed.
The context manager’s __exit__() method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to __exit__(). Otherwise, three Nonearguments are supplied.
If the suite was exited due to an exception, and the return value from the __exit__() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement.
If the suite was exited for any reason other than an exception, the return value from __exit__() is ignored, and execution proceeds at the normal location for the kind of exit that was taken.
With more than one item, the context managers are processed as if multiple with statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
http://docs.python.org/2/reference/compound_stmts.html#with
Python积木之with的更多相关文章
- RF源码阅读(碎片纪录)-Python积木之contextlib
参考页面: http://docs.python.org/2/library/contextlib.html contextlib是为了配合with语句来使用的.使用起来更加简洁.本来想写一下,这位同 ...
- Python的单元测试(一)
title: Python的单元测试(一) author: 青南 date: 2015-02-27 22:50:47 categories: Python tags: [Python,单元测试] -- ...
- [转]大数据时代,python竟是最好的语言?
随着大数据疯狂的浪潮,新生代的工具Python得到了前所未有的爆发.简洁.开源是这款工具吸引了众多粉丝的原因.目前Python最热的领域,非数据分析和挖掘莫属了.从以Pandas为代表的数据分析领 ...
- Python之路【第五篇】:面向对象编程
面向对象编程思维导向图
- Python之路【第四篇补充】:面向对象初识和总结回顾
面向过程的编程 面向过程:根据业务逻辑从上到下写垒代码! 例子: 需求一.有一个程序需要做身份认证: 用户名有个字典: #定义一个用户名信息字典 user_info = { "zhangsa ...
- Python之路【第三篇】:Python基础(二)
函数的理解 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 函数作用是你的程序有良好的扩展性.复用性. 同样的功能要是用3次以上的话就建议 ...
- python中getattr函数 hasattr函数
hasattr(object, name)作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的).示例: > ...
- python中的内置函数getattr()
在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribu ...
- Python 第六篇(上):面向对象编程初级篇
面向:过程.函数.对象: 面向过程:根据业务逻辑从上到下写垒代码! 面向过程的编程弊:每次调用的时候都的重写,代码特别长,代码重用性没有,每次增加新功能所有的代码都的修改!那有什么办法解决上面出现的弊 ...
随机推荐
- [eclipse]改项目名称后tomcat连接问题解决方法
背景:在我们使用eclipse进行项目开发时,有时候会需要修改项目名称,当改动项目名称后发现tomcat启动访问出现问题,使用新的项目名称不可行,使用旧的项目名称却可以.修改web.xml里面的dis ...
- [转] Paxos算法2-算法过程(实现)
请先参考前文:Paxos算法1 1.编号处理 根据P2c ,proposer在提案前会先咨询acceptor查看其批准的最大的编号和value,再决定提交哪个value.之前我们一直强调更高编号的pr ...
- 集算器协助java处理多样性数据源之MongoDB
MongoDB不支持join,其官网上推荐的unity jdbc可以把数据取出来进行二次计算实现join运算,但这些join.group.函数.表达式等高级功能都是收费版才有,而且即使是收费版本,对子 ...
- C标准头文件<assert.h>
<assert.h>定义了两个用来调试程序的宏: assert和NDEBUG,assert用来判断表达式是否为真,如果为真继续执行,如果为假,向stderr输出一条错误消息,并调用< ...
- mysql、sql server、oracle数据库分页查询及分析(操作手册)
1.mysql分页查询 方式1: select * from table order by id limit m, n; 该语句的意思为,查询m+n条记录,去掉前m条,返回后n条记录.无疑该查询能够实 ...
- 使用flume的一个例子
新项目中需要使用到hadoop和vertica,使用flume把数据加载到hadoop中,我做了一个例子, 即监控一个sharefolder,如果里面有文件,则会文件load到hadoop. 开启Fl ...
- FIR数据广播结构-提高时钟速率
直接型的信号流图 采用转置得到广播结构的信号流图 对于一个常系数四阶的FIR滤波器 直接型的RT L结构如下: 转置后的RTL结构
- [ZZ]Sign Up for the First-Ever Appium Roadshow on August 20th in New York City
http://sauceio.com/index.php/2014/07/appium-roadshow-nyc/?utm_source=feedly&utm_reader=feedly&am ...
- jquery实现整屏翻屏效果:jquery.mousewheel(一)
实现整屏上下翻效果:需加载的js <script type="text/javascript" src="js/jquery-1.8.3.min.js"& ...
- AC日记——逃跑的拉尔夫 codevs 1026 (搜索)
1026 逃跑的拉尔夫 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题解 题目描述 Description 年轻的拉尔夫开玩笑地从一 ...