python 中with的使用
#!/usr/bin/python#coding:utf8#-------------------------------------------------------------------------------# Name:python中异常的处理与跑抛出# Author:quan# Created:21/09/2013#---------
·
#!/usr/bin/python
#coding:utf8
#-------------------------------------------------------------------------------
# Name: python中异常的处理与跑抛出
# Author: quan
# Created: 21/09/2013
#-------------------------------------------------------------------------------
#python中的with的使用,
"""
python中with可以明显改进代码友好度,比如:
[python] view plaincopyprint?
with open('a.txt') as f:
print f.readlines()
为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:
[python] view plaincopyprint?
>>> 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:
[python] view plaincopyprint?
>>> 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 用处不大
[python] view plaincopyprint?
from contextlib import closing
import urllib
with closing(urllib.urlopen('http://www.python.org')) as page:
for line in page:
print line
"""
#自己写的事例
#首先定义一个类
class with_python():
#初始化一个数组的,类型行
def __init__(self,list_name):
self.list = list_name
#定义with调用函数(使用with必有得选项)
def __enter__(self):
self.aa = self.list
return self.aa
#退出选项 (使用with必有得选项)
def __exit__(self,type,value,tb):
if type == None:
self.list = self.aa
return False
item = [1,2,]
#进行上下为管理
with with_python(item) as list_one:
list_one.append(1)
list_one.append(3)
list_one.pop(0)
print list_one
print item
更多推荐
已为社区贡献15条内容
所有评论(0)