Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2112701
  • 博文数量: 333
  • 博客积分: 10161
  • 博客等级: 上将
  • 技术积分: 5238
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-19 08:59
文章分类

全部博文(333)

文章存档

2017年(10)

2014年(2)

2013年(57)

2012年(64)

2011年(76)

2010年(84)

2009年(3)

2008年(37)

分类: LINUX

2014-01-06 13:10:32

 

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.   
  7. >>> with A() as a:  
  8.     print 'in with'  
  9.   
  10. in enter  
  11. in with  
  12. 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.   
  4. with closing(urllib.urlopen('')) as page:  
  5.     for line in page:  
  6.         print line  
阅读(4360) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~