@python 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:
1 #-*- coding:utf-8 -*- 2 from __future__ import with_statement 3 from contextlib import contextmanager 4 5 @contextmanager 6 def context(): 7 print 'entering the zone' 8 try: 9 yield 10 except Exception,e: 11 print 'with an error %s ..' % e 12 raise e 13 else: 14 print 'with no error' 15 16 #实用 17 with context(): 18 print '----------in context call-------'
结果:
entering the zone
----------in context call-------
with no error
使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大