简而言之,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]
  1. The context expression (the expression given in the with_item) is evaluated to obtain a context manager.

  2. The context manager’s __exit__() is loaded for later use.

  3. The context manager’s __enter__() method is invoked.

  4. 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.

  5. The suite is executed.

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

  1. RF源码阅读(碎片纪录)-Python积木之contextlib

    参考页面: http://docs.python.org/2/library/contextlib.html contextlib是为了配合with语句来使用的.使用起来更加简洁.本来想写一下,这位同 ...

  2. Python的单元测试(一)

    title: Python的单元测试(一) author: 青南 date: 2015-02-27 22:50:47 categories: Python tags: [Python,单元测试] -- ...

  3. [转]大数据时代,python竟是最好的语言?

      随着大数据疯狂的浪潮,新生代的工具Python得到了前所未有的爆发.简洁.开源是这款工具吸引了众多粉丝的原因.目前Python最热的领域,非数据分析和挖掘莫属了.从以Pandas为代表的数据分析领 ...

  4. Python之路【第五篇】:面向对象编程

    面向对象编程思维导向图

  5. Python之路【第四篇补充】:面向对象初识和总结回顾

    面向过程的编程 面向过程:根据业务逻辑从上到下写垒代码! 例子: 需求一.有一个程序需要做身份认证: 用户名有个字典: #定义一个用户名信息字典 user_info = { "zhangsa ...

  6. Python之路【第三篇】:Python基础(二)

    函数的理解 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 函数作用是你的程序有良好的扩展性.复用性. 同样的功能要是用3次以上的话就建议 ...

  7. python中getattr函数 hasattr函数

    hasattr(object, name)作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的).示例: > ...

  8. python中的内置函数getattr()

    在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribu ...

  9. Python 第六篇(上):面向对象编程初级篇

    面向:过程.函数.对象: 面向过程:根据业务逻辑从上到下写垒代码! 面向过程的编程弊:每次调用的时候都的重写,代码特别长,代码重用性没有,每次增加新功能所有的代码都的修改!那有什么办法解决上面出现的弊 ...

随机推荐

  1. SAM4E单片机之旅——23、在AS6(GCC)中使用FPU

    浮点单元(Floating Point Unit,FPU),是用于处理浮点数运算的单元. 为使用FPU,除了需要启用FPU外,还需要对编译器进行设置,以使其针对浮点运算生成特殊的指令.虽然在Atmel ...

  2. Effective Java 05 Avoid creating unnecessary objects

    String s = new String("stringette"); // Don't do this. This will create an object each tim ...

  3. 用java程序输出自己的姓名

    代码部分: public class Hello { public static void main(String[] args) { System.out.println("$$$$$$$ ...

  4. c#,关于Big Endian 和 Little Endian,以及转换类

    Big Endian:最高字节在地址最低位,最低字节在地址最高位,依次排列. Little Endian:最低字节在最低位,最高字节在最高位,反序排列. 当在本地主机上,无需注意机器用的是Big En ...

  5. SQL Server 2008 R2——VC++ ADO 操作 事务

    ==================================声明================================== 本文原创,转载在正文中显要的注明作者和出处,并保证文章的完 ...

  6. CSS盒模型重新理解篇

    最近比较闲,思索着怎么提高下JS技术,于是找到了昵称为豪情的这哥们的一篇文章,应该是哥们吧,详细了解了下,发现其中的试题CSS部分有些做起来很吃力,于是乎各种google恶补盒模型,找到了这哥们的一文 ...

  7. 在Jena框架下基于MySQL数据库实现本体的存取操作

    在Jena框架下基于MySQL数据库实现本体的存取操作 转自:http://blog.csdn.net/jtz_mpp/article/details/6224311 最近在做一个基于本体的管理系统. ...

  8. KEIL与ADS1.2共存

    出现的问题: 原来电脑已经安装了ADS1.2.现在安装keil5编译一个32位新唐单片机程序时,出现了如下错误: Error: L6411E: No compatible library exists ...

  9. uniq

    -c, --count 在每行前加上表示相应行目出现次数的前缀编号-d, --repeated 只输出重复的行-D, --all-repeated[=delimit-method 显示所有重复的行de ...

  10. Hive UDF’S addMonths

    our project use hive 0.10 , and in the hiveql , we need use addMonths function builtin in hive-0.11. ...