网站首页 网站建设 IT知识 IT知识教程 Python with用法实例

Python with用法实例

2021-05-22 21:27:34

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。 如涉及版权问题,请提交至online#300.cn邮箱联系删除。

以上产品还未完全满足我的所有需求,在下方提交我的专属需求
我的专属需求:
*手机号:
*验证码:
img
咨询报价
现在咨询
img

在线咨询

建站在线咨询

img

微信咨询

扫一扫添加
动力姐姐微信

img
img

TOP