Python with as特别用法介绍
Python with as特别用法介绍:
要打开一个文件,我习惯照书本教的用以下代码
fobj = open(filename, 'r')
怕文件不存在,可能还得再加个捕捉错误
try:
fobj = open(filename, 'r')
except IOError:
pass
但有了with as 就方便多了,可以用以下代码
with open(filename, 'r') as fobj:
do something
为了让class 也能使用,需添加二个函数__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
使用模组contextlib,便不用构造__enter__和 __exit__
>>> 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
官方范例
from contextlib import contextmanager
@contextmanager
def tag(name):
print "<%S>
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
