python with用法

扫码查看

python中with可以明显改进代码友好度,比如:

  1. with open('a.txt') as f:
  2. print f.readlines()

为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:

  1. >>> class A:
  2. def __enter__(self):
  3. print 'in enter'
  4. def __exit__(self, e_t, e_v, t_b):
  5. print 'in exit'
  6. >>> with A() as a:
  7. print 'in with'
  8. in enter
  9. in with
  10. in exit

另外python库中还有一个模块contextlib,使你不用构造含有__enter__, __exit__的类就可以使用with:

  1. >>> from contextlib import contextmanager
  2. >>> from __future__ import with_statement
  3. >>> @contextmanager
  4. ... def context():
  5. ...     print 'entering the zone'
  6. ...     try:
  7. ...         yield
  8. ...     except Exception, e:
  9. ...         print 'with an error %s'%e
  10. ...         raise e
  11. ...     else:
  12. ...         print 'with no error'
  13. ...
  14. >>> with context():
  15. ...     print '----in context call------'
  16. ...
  17. entering the zone
  18. ----in context call------
  19. with no error

使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大

    1. from contextlib import closing
    2. import urllib
    3. with closing(urllib.urlopen('http://www.python.org')) as page:
    4. for line in page:
    5. print line
04-26 00:19
查看更多