Python with用法实例

yipeiwu_com5年前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 TF-IDF算法实现文本关键词提取

TF(Term Frequency)词频,在文章中出现次数最多的词,然而文章中出现次数较多的词并不一定就是关键词,比如常见的对文章本身并没有多大意义的停用词。所以我们需要一个重要性调整系...

Selenium定位元素操作示例

本文实例讲述了Selenium定位元素操作。分享给大家供大家参考,具体如下: Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在...

让python的Cookie.py模块支持冒号做key的方法

为了做好兼容性,只能选择兼容:冒号。 很简单,修改一下Cookie.Morsel 复制代码 代码如下: #!/usr/bin/python # -*- coding: utf-8 -*-...

python 接口测试response返回数据对比的方法

背景:之前写的接口测试一直没有支持无限嵌套对比key,上次testerhome逛论坛,有人分享了他的框架,看了一下,有些地方不合适我这边自己修改了一下,部署在jenkins上跑完效果还不...

python继承和抽象类的实现方法

本文实例讲述了python继承和抽象类的实现方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:#!/usr/local/bin/python # Fig 9.9: f...