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 通过打码平台实现验证码的实现

 在爬虫时,经常遇到登录需要验证码的情况,简单的验证码可以自己解决,复制的验证码需要借助机器学习,有一定的难度。还有一个简单的方案就是采用付费的打码平台。 比如R若快(http...

python如何通过实例方法名字调用方法

本文实例为大家分享了python通过实例方法名字调用方法的具体代码,供大家参考,具体内容如下 案例:        某项目中,...

python字典多条件排序方法实例

项目编写过程中,总能遇见对字典进行排序什么的,如果要实现多条件排序只需要下面几行代码实现。充分体现了python的好处了。 复制代码 代码如下: teamitems = [{'team'...

Python 如何访问外围作用域中的变量

在表达式中引用变量时,Python 会按照如下的顺序遍历各个作用域,寻找该变量: 当前函数作用域 任何外围作用域(比如包含当前函数的其他函数) global 作用域,即代码...

详解使用python的logging模块在stdout输出的两种方法

详解使用python的logging模块在stdout输出 前言:   使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志...