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实现生成随机数据插入mysql数据库的方法

Python实现生成随机数据插入mysql数据库的方法

本文实例讲述了Python实现生成随机数据插入mysql数据库的方法。分享给大家供大家参考,具体如下: 运行结果: 实现代码: import random as r import...

python中的tcp示例详解

python中的tcp示例详解

TCP简介 TCP介绍 TCP协议,传输控制协议(英语:Transmission Control Protocol,缩写为 TCP)是一种面向连接的、可靠的、基于字节流的传输层通信协...

python实现简单聊天应用 python群聊和点对点均实现

python实现简单聊天应用 python群聊和点对点均实现

后续代码更新和功能添加会提交到个人github主页,有兴趣可以一起来完善! 如果只是拿过去运行看结果,请注意平台相关性以及python版本号,本示例开发运行平台为win7x86_64 p...

Python httplib模块使用实例

httplib模块是一个底层基础模块,实现的功能比较少,正常情况下比较少用到.推荐用urllib, urllib2, httplib2. HTTPConnection 对象 class...

Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)

环境: Python3.7 依赖库: import datetime import random import requests import hashlib import json...