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 

相关文章

Django使用中间键实现csrf认证详解

Django中的csrf认证实现的原理 调用 process_view 方法 检查视图是否被 @csrf_exempt (免除csrf认证) - 去请求体或cookie中获取toke...

python 动态迁移solr数据过程解析

python 动态迁移solr数据过程解析

前言 上项目的时候,遇见一次需求,需要把在线的 其中一个 collection 里面的数据迁移到另外一个collection下,于是就百度了看到好多文章,其中大部分都是使用导入的方法,没...

详解Python3 中的字符串格式化语法

一、旧式的字符串格式化 % 操作符 参考以下示例: >>> name = "Eric" >>> "Hello, %s." % name 'He...

Python读写txt文本文件的操作方法全解析

Python读写txt文本文件的操作方法全解析

一、文件的打开和创建 >>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhel...

python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能

python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能

1、代码1: (1)进度条等显示在主窗口状态栏的右端,代码如下: from PyQt5.QtWidgets import QMainWindow, QProgressBar, QAp...