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发送HTTP请求的方法小结

本文实例讲述了python发送HTTP请求的方法。分享给大家供大家参考。具体如下: 这里包含 Python 使用 GET/HEAD/POST 方法进行 HTTP 请求 1. GET 方法...

python使用cPickle模块序列化实例

本文实例讲述了python使用cPickle模块序列化的方法,分享给大家供大家参考。 具体方法如下: import cPickle data1 = ['abc',12,23] #几...

Golang GBK转UTF-8的例子

问题:在 Golang 的调试过程中出现中文乱码 原因:Golang 默认不支持 UTF-8 以外的字符集 解决:将字符串的编码转换成UTF-8 首先需要 mahonia 这个包...

Python+tkinter模拟“记住我”自动登录实例代码

Python+tkinter模拟“记住我”自动登录实例代码

本文分享的代码主要是通过Python+tkinter模拟“记住我”自动登录的功能,具体介绍如下。 基本思路:如果某次登录成功,则创建临时文件记录有关信息,每次启动程序时尝试自动获取上次登...

用TensorFlow实现lasso回归和岭回归算法的示例

用TensorFlow实现lasso回归和岭回归算法的示例

也有些正则方法可以限制回归算法输出结果中系数的影响,其中最常用的两种正则方法是lasso回归和岭回归。 lasso回归和岭回归算法跟常规线性回归算法极其相似,有一点不同的是,在公式中增加...