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 第六篇(上):面向对象编程初级篇
面向:过程.函数.对象: 面向过程:根据业务逻辑从上到下写垒代码! 面向过程的编程弊:每次调用的时候都的重写,代码特别长,代码重用性没有,每次增加新功能所有的代码都的修改!那有什么办法解决上面出现的弊 ...
随机推荐
- chrome和搜狗浏览器的js问题
1.在chrome中如果是js添加颜色必须用"#00CC00",必须加#号...不然会出问题,但是在搜狗浏览器中可以没有#号也能正确识别...
- LevelDB源码分析--使用Iterator简化代码设计
我们先来参考来至使用Iterator简化代码2-TwoLevelIterator的例子,略微修改希望能帮助更加容易立即,如果有不理解请各位看客阅读原文. 下面我们再来看一个例子,我们为一个书店写程序, ...
- 关于zend_parse_parameters函数
PHP_FUNCTION(set_time_limit) { long new_timeout; char *new_timeout_str; int new_timeout_strlen; if ( ...
- Apache2.4和Apache2.2访问控制配置语法对比
一.访问控制 在Apache2.2版本中,访问控制是基于客户端的主机名.IP地址以及客户端请求中的其他特征,使用Order(排序), Allow(允许), Deny(拒绝),Satisfy(满足)指令 ...
- pageX和pageY
pageX() 属性是鼠标指针的位置,相对于文档的左边缘. pageY() 属性是鼠标指针的位置,相对于文档的上边缘. 例1 $(document).mousemove(function(e){ $( ...
- 入门 ARM 汇编(一)—— 知识铺垫
我读着史铁生的散文,零碎的牵扯起我生命中不曾出现过的记忆,一如北方的黄山厚土之中悠忽而来的忧伤的信天游,那些灿若信仰一样的阳光以及阳光下虔诚的子民.我想有一次远行,于细碎流淌的时光与路途之中,观察所有 ...
- Spring4定时器 cronTrigger和simpleTrigger实现方法
spring4定时器 cronTrigger和simpleTrigger实现方法 Quartz 是个开源的作业调度框架,为在 Java 应用程序中进行作业调度提供了简单却强大的机制.Quartz 允许 ...
- Windows Live Writer离线编写博客
WLW最新版本为2012,官网下载 Windows Live Writer配置步骤 使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结 L ...
- redis unwatch discard
UNWATCH UNWATCH 取消 WATCH 命令对所有 key 的监视. 如果在执行 WATCH 命令之后, EXEC 命令或 DISCARD 命令先被执行了的话,那么就不需要再执行UNWATC ...
- 双向广搜+hash+康托展开 codevs 1225 八数码难题
codevs 1225 八数码难题 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题目描述 Description Yours和zero在研究A*启 ...