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如何解析配置文件并应用到项目中

配置文件的类型 通常自动化测试中的配置文件是以.ini 和 .conf 为后缀的文件 配置文件的组成 1.section 2.option 3.value 配置文件的格式 [s...

python3实现在二叉树中找出和为某一值的所有路径(推荐)

python3实现在二叉树中找出和为某一值的所有路径(推荐)

请写一个程序创建一棵二叉树,并按照一定规则,输出二叉树根节点到叶子节点的路径。 规则如下: 1、从最顶端的根结点,到最下面的叶子节点,计算路径通过的所有节点的和,如果与设置的某一值的相同...

python编写计算器功能

python编写计算器功能

本文实现用python编写一个带界面的计算器小程序,当然这个计算器功能很简单,只能进行一些简单的数学运算,很适合初学者,希望能给大家带来一些启发 实验前提 因为是带图形界面的,所以...

python-OpenCV 实现将数组转换成灰度图和彩图

python-OpenCV 实现将数组转换成灰度图和彩图

主要步骤 1.生成普通python数组(bytearray(),os.urandom()) 2.转换成numpy数组(numpy.array()) 3.通过reshape将数组转换到所需...

Python 机器学习库 NumPy入门教程

NumPy是一个Python语言的软件包,它非常适合于科学计算。在我们使用Python语言进行机器学习编程的时候,这是一个非常常用的基础库。 本文是对它的一个入门教程。 介绍 NumP...