The More I Learn, The Less I Know, Tracking Mind Only With Code
2011-10-27 13:28 35895人阅读 评论(5)
python中with可以明显改进代码友好度,比如:
with open('a.txt') as f:
printf.readlines()
为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:
>>>classA:
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'
inenter
inwith
inexit
另外python库中还有一个模块contextlib,使你不用构造含有__enter__, __exit__的类就可以使用with:
>>>fromcontextlibimportcontextmanager
>>> from__future__importwith_statement
>>> @contextmanager
... defcontext():
... print'entering the zone'
... try:
... yield
... exceptException, e:
... print'with an error %s'%e
... raisee
... else:
... print'with no error'
...
>>> with context():
... print'----in context call------'
...
entering the zone
----incontext call------
with no error
使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大
fromcontextlibimportclosing
importurllib
with closing(urllib.urlopen('http://www.python.org')) as page:
forlineinpage:
printline
版权声明:本文为博主原创文章,未经博主允许不得转载。
查看评论5楼 飞越蓝天的云 2015-04-23 18:53发表 [回复]
还不错!刚刚用过!4楼 OuZhengguang 2014-05-29 17:01发表 [回复]
主要是yield在这里的作用3楼 OuZhengguang 2014-05-29 16:57发表 [回复]
对那个yield还是不是很清楚,求楼主解释解释啊:)2楼 Bird_1989 2013-11-11 10:01发表 [回复]
挺好,我好像懂了点1楼 caiss 2013-01-17 17:51发表 [回复]
确实好用啊,不知道这个和普通的用法性能上有什么区别,测试一下看看
您还没有登录,请[登录]或[注册]
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
个人资料
访问:266904次
积分:3905
等级:
排名:第3806名
原创:137篇
转载:16篇
译文:2篇
评论:46条文章搜索文章分类文章存档阅读排行评论排行推荐文章最新评论_tears_: 你这是那个版本呀?我测试4.1 和 3.8 都不行,怎么回事???
perlove6: 你好,有个问题不明白,在“在备选master和slave节点 crontab -e 添加计划任务”,...
1000sprites: all_tokens = sum(texts, []),这句话没有报错吗?
杰Tang_fighting: @frank_cg:计算机程序的构造和解释练习题1.19
霜之咏叹调: 哥们,你还在吗?我首先尝试使用git-svn了,但是公司的svn权限很扯淡,没法用。最后考虑用你的方...网站客服杂志客服微博客服webmaster@csdn.net400-600-2320|北京创新乐知信息技术有限公司 版权所有|江苏乐知网络技术有限公司 提供商务支持
京 ICP 证 070598 号|Copyright 1999-2014, CSDN.NET, All Rights Reserved