Python with用法实例

yipeiwu_com6年前Python基础

python中with可以明显改进代码友好度,比如:

复制代码 代码如下:

with open('a.txt') as f: 
    print f.readlines() 

为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:
复制代码 代码如下:

>>> class A: 
    def __enter__(self): 
        print 'in enter' 
    def __exit__(self, e_t, e_v, t_b): 
        print 'in exit' 
 
>>> with A() as a: 
    print 'in with' 
 
in enter 
in with 
in exit 

另外python库中还有一个模块contextlib,使你不用构造含有__enter__, __exit__的类就可以使用with:
复制代码 代码如下:

>>> from contextlib import contextmanager 
>>> from __future__ import with_statement 
>>> @contextmanager 
... def context(): 
...     print 'entering the zone' 
...     try: 
...         yield 
...     except Exception, e: 
...         print 'with an error %s'%e 
...         raise e 
...     else: 
...         print 'with no error' 
... 
>>> with context(): 
...     print '----in context call------' 
... 
entering the zone 
----in context call------ 
with no error 

使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大
复制代码 代码如下:

from contextlib import closing 
import urllib 
 
with closing(urllib.urlopen('http://www.python.org')) as page: 
    for line in page: 
        print line 

相关文章

Python脚本实现虾米网签到功能

Python脚本实现虾米网签到功能

本文实例讲述了Python脚本实现虾米网签到功能的方法。分享给大家供大家参考,具体如下: 概述 这个脚本完成了自动登录虾米网、签到的功能。 大致要用到urllib、urllib2、coo...

python实现挑选出来100以内的质数

这里给大家分享的是使用python实现将100以内的质数挑选出来 代码非常简单,就不多废话了。 """ 使用filter将100以内的质数挑选出来 """ # coding =...

python分析作业提交情况

python分析作业提交情况

这次做一个比较贴近我实际的东西:python分析作业提交情况。 要求:     将服务器中交作业的学生(根据文件的名字进行提取)和统计成绩的表格中...

Python实现矩阵转置的方法分析

Python实现矩阵转置的方法分析

本文实例讲述了Python实现矩阵转置的方法。分享给大家供大家参考,具体如下: 前几天群里有同学提出了一个问题:手头现在有个列表,列表里面两个元素,比如[1, 2],之后不断的添加新的列...

python的即时标记项目练习笔记

python的即时标记项目练习笔记

这是《python基础教程》后面的实践,照着写写,一方面是来熟悉python的代码方式,另一方面是练习使用python中的基本的以及非基本的语法,做到熟能生巧。 这个项目一开始比较简单,...