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中非常重要的数据结构,因其用哈希的方式存储数据,其复杂度为O(1),速度非常快。下面列出字典的常用的用途. 一、字典中常见方法列...

结合OpenCV与TensorFlow进行人脸识别的实现

结合OpenCV与TensorFlow进行人脸识别的实现

作为新手来说,这是一个最简单的人脸识别模型,难度不大,代码量也不算多,下面就逐一来讲解,数据集的准备就不多说了,因人而异。 一. 获取数据集的所有路径 利用os模块来生成一个包含所有数据...

pycharm中使用anaconda部署python环境的方法步骤

pycharm中使用anaconda部署python环境的方法步骤

今天来说一下python中一个管理包很好用的工具anaconda,可以轻松实现python中各种包的管理。相信大家都会有这种体验,在pycharm也是有包自动搜索和下载的功能,这个我在前...

python进阶教程之循环相关函数range、enumerate、zip

在“循环”一节,我们已经讨论了Python基本的循环语法。这一节,我们将接触更加灵活的循环方式。 range() 在Python中,for循环后的in跟随一个序列的话,循环每次使用的序列...

scrapy自定义pipeline类实现将采集数据保存到mongodb的方法

本文实例讲述了scrapy自定义pipeline类实现将采集数据保存到mongodb的方法。分享给大家供大家参考。具体如下: # Standard Python library im...