简而言之,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. 在js中获取get参数(仿PHP)

    复制粘贴即可..然后就可以在js中像PHP用$_GET['name']这样子获取get参数了!! /*--------------------(返回 $_GET 对象, 仿PHP模式)-------- ...

  2. INFORMATICA 的调优之 INFORMATICA SERVER TUNING

    INFORMATICA SERVER的调优我认为主要从两个级别来做,一个是MAPPING级别,一个是SESSION级别. 对于MAPPING级别的调优: 一  对MAPPING数据流向的优化: 1 控 ...

  3. 图解 SQL 各种连接查询之间的区别

    转载自:http://blog.csdn.net/xuanjiewu/article/details/50636465 对于SQL的Join,在学习起来可能是比较乱的.我们知道,SQL的Join语法有 ...

  4. MemSQL分布式架构介绍(二)

    接上次的MemSQL分布式架构介绍(一),原文在这里:http://docs.memsql.com/latest/concepts/distributed_architecture/ 首先上张图,是我 ...

  5. 问题解决——Group Box控件遮挡其他控件

    转载请保持文章的完整性并显要地注明出处 本文链接:http://blog.csdn.net/wlsgzl/article/details/38042301 ====================== ...

  6. 问题解决——使用GP-3120TN打印条形码标签

    终于大致的尝试出了参数和编程手册里指令的使用. 在这里,感谢佳博中一个叫做"Gprinter 陶玮"的工程师所提供的技术支持.非常感谢,如果没有你,在写这篇文章之前我可能换别的打印 ...

  7. MySQL中的FEDERATED引擎

    首先说明>     FEDERATED存储引擎访问在远程数据库的表中的数据,而不是本地的表.这个特性给某些开发应用带来了便利,你可以直接在本地构建一个federated表来连接远程数据表,配置好 ...

  8. Vert.x入门体验

    Vert.x入门体验 一.概述 Vert.x(http://vertx.io)是一个基于JVM.轻量级.高性能的应用平台,非常适用于最新的移动端后台.互联网.企业应用架构. 二.安装配置 访问Vert ...

  9. DataGridView合并单元格

    昨天一个同事问我DataGridView单元格合并的问题,一开始按照我的设想是算出两个单元格的Rectangle,然后直接使用e.Graphics.FillRectangle(backColorBru ...

  10. Astyle编程语言格式化工具的中文说明

    Artistic Style 1.23Maintained by: Jim PatteeOriginal Author: Tal Davidson Usage  :  astyle [options] ...