Python with用法实例
更新时间:2015年04月14日 09:38:45 投稿:junjie
这篇文章主要介绍了Python with用法实例,本文讲解了with语句的几种使用方法和使用场景,需要的朋友可以参考下
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
相关文章
requests库post方法如何传params类型的参数(最新推荐)
在使用requests库的post方法时,params类型的参数用于在URL中作为查询字符串传递,与data或json参数不同,后者是放在请求体中的,params参数接受一个字典或包含键值对的序列,本文给大家介绍requests库post方法怎么传params类型的参数,感兴趣的朋友一起看看吧2025-03-03
PyCharm2021最新激活码+激活码补丁(亲测最新版PyCharm2021.3激活成功)
这篇文章主要介绍了PyCharm2021最新激活码+激活码补丁,亲测最新版PyCharm2021.3激活成功,PyCharm2020激活成功2020-09-09
解决python访问报错:jinja2.exceptions.TemplateNotFound:index.html
这篇文章主要介绍了解决python访问报错:jinja2.exceptions.TemplateNotFound:index.html,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2023-12-12
Python 如何将integer转化为罗马数(3999以内)
这篇文章主要介绍了Python 将integer转化为罗马数(3999以内)的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06


最新评论