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 第六篇(上):面向对象编程初级篇
面向:过程.函数.对象: 面向过程:根据业务逻辑从上到下写垒代码! 面向过程的编程弊:每次调用的时候都的重写,代码特别长,代码重用性没有,每次增加新功能所有的代码都的修改!那有什么办法解决上面出现的弊 ...
随机推荐
- 抓包工具charles使用教程指南
0x01 前言: Charles是一款抓包修改工具,相比起burp,charles具有界面简单直观,易于上手,数据请求控制容易,修改简单,抓取数据的开始暂停方便等等优势!下面来详细介绍下这款强大好用的 ...
- Android开源项目汇总【转】
主要介绍那些不错个性化的View,包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView.ProgressBar.TextView ...
- java控制台输入
一.java控制台输入 java控制台输入有如下几个方法 1.JDK 1.4 及以下版本读取的方法 JDK 1.4 及以下的版本中要想从控制台中输入数据只有一种办法,即使用System.in获得系统的 ...
- cocos2d-x之物理按键初试
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } auto listener=EventListenerKeyboar ...
- 怎么通过 Microsof Office Project 2010 来写功能开发计划
新建一个Microsof Office Project 2010 功能, 直接填写,可以通过快捷键来改变目录分级情况.(shift+alt+ —> 或者 <—) 也可以通过导航栏上面的摘要 ...
- nyoj 230/poj 2513 彩色棒 并查集+字典树+欧拉回路
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=230 题意:给你许许多多的木棍,没条木棍两端有两种颜色,问你在将木棍相连时,接触的端点颜色 ...
- jquery获取复选框(checkbox)的选中值(一组和单个)
使用jquery获取一组或者单个checkbox的选中状态的值.下面通过一个示例进行说明,假设现有一页面有一组checkbox的name的值为id,那么获取这组name=id的checkbox的值的方 ...
- fdtd simulation, plotting with gnuplot, writting in perl
# 9月13日 于成都黄龙溪 1 #!/usr/bin/perl # Author : Leon Email: yangli0534@gmail.com # fdtd simulation , plo ...
- 【ASP.NET 进阶】定时执行任务实现 (定时读取和修改txt文件数字内容,无刷新显示结果)
现在有很多网站或系统需要在服务端定时做某件事情,如每天早上8点半清理数据库中的无效数据等等,Demo 具体实现步骤如下: 0.先看解决方案截图 1.创建ASP.NET项目TimedTask,然后新建一 ...
- Rem实现自适应初体验
第一次做移动端的页面,遇到的第一个问题就是移动端的轮播图.其实轮播图的插件有很多,但是完全满足需求的并不容易找. 需求: 1.实现基本的触屏轮播图效果 2.传入非标准比例的图片,可以自动平铺(有时候图 ...