python with 用法

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

[python]  view plain copy print ?
  1. with open('a.txt') as f:  
  2.     print f.readlines()  

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

[python]  view plain copy print ?
  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:

[python]  view plain copy print ?
  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 用处不大

[python]  view plain copy print ?
  1. from contextlib import closing  
  2. import urllib  
  3.   
  4. with closing(urllib.urlopen('http://www.python.org')) as page:  
  5.     for line in page:  
  6.         print line  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值