码迷,mamicode.com
首页 > 编程语言 > 详细

Python with语句

时间:2014-09-10 22:20:31      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   for   文件   div   sp   

with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。

示例:

  with open(r‘somefileName‘) as somefile:
        for line in somefile:
            print line
            # ...more code

自定义应用:

    class DummyResource:
    def __init__(self, tag):
            self.tag = tag
            print ‘Resource [%s]‘ % tag
        def __enter__(self):
            print ‘[Enter %s]: Allocate resource.‘ % self.tag
            return self      # 可以返回不同的对象
        def __exit__(self, exc_type, exc_value, exc_tb):
            print ‘[Exit %s]: Free resource.‘ % self.tag
            if exc_tb is None:
                print ‘[Exit %s]: Exited without exception.‘ % self.tag
            else:
                print ‘[Exit %s]: Exited with exception raised.‘ % self.tag
                return False   # 可以省略,缺省的None也是被看做是False

 

  

Python with语句

标签:style   blog   color   io   使用   for   文件   div   sp   

原文地址:http://www.cnblogs.com/mengyixuan/p/3965240.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!