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 base64 decode incorrect padding错误解决方法

python的base64.decodestring方法做base64解码时报错: 复制代码 代码如下: Traceback (most recent call last):  ...

python3.7.0的安装步骤

python3.7.0的安装步骤

如何安装Python的操作步骤: 1.第一步先去python的官方网站下载python的安装包 地址: https://www.python.org/downloads/ 根据自己的系...

c++生成dll使用python调用dll的方法

第一步,建立一个CPP的DLL工程,然后写如下代码,生成DLL 复制代码 代码如下:#include <stdio.h>     #d...

Python的requests网络编程包使用教程

Python的requests网络编程包使用教程

早就听说requests的库的强大,只是还没有接触,今天接触了一下,发现以前使用urllib,urllib2等方法真是太搓了…… 这里写些简单的使用初步作为一个记录 一、下载 官方项目...

利用python画一颗心的方法示例

利用python画一颗心的方法示例

前言 Python一般使用Matplotlib制作统计图形,用它自己的说法是‘让简单的事情简单,让复杂的事情变得可能'。用它可以制作折线图,直方图,条形图,散点图,饼图,谱图等等你能想到...