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  
  • 相关阅读:
    VS自带的dbghelp.h文件 报错
    Windows 自带的截屏功能
    CentOS 7 安装
    Windows 远程连接 CentOS 7 图形化桌面
    <<、|=、&的小例子
    pip 安装库过慢
    pip -i 和 -U 参数
    windows下安装TA-Lib库
    vector、map 判断某元素是否存在、查找指定元素
    vector push_back报错
  • 原文地址:https://www.cnblogs.com/skying555/p/4518609.html
Copyright © 2011-2022 走看看