zoukankan      html  css  js  c++  java
  • python with用法

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

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


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

    [python] view plaincopyprint?
     
    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 plaincopyprint?
     
    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 plaincopyprint?
     
      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  
  • 相关阅读:
    显示多行字符串
    dowhile
    获取系统的相关文件夹
    DLL 实际应用版本
    ShellExecute
    LoadLibrary
    MFC DLL的创建
    在DLL中存放资源
    替换字符串
    RemoveDirectoryB
  • 原文地址:https://www.cnblogs.com/skying555/p/4518609.html
Copyright © 2011-2022 走看看