zoukankan      html  css  js  c++  java
  • python语法-[with来自动释放对象]

    python语法-[with来自动释放对象]

    http://www.cnblogs.com/itech/archive/2011/01/13/1934779.html

    一 with

    python中的with的作用是自动释放对象,即使对象在使用的过程中有异常抛出。可以使用with的类型必须实现__enter__ __exit__。我的理解是=try...finally{},在finally中调用了释放函数。

    [类似与CSharp中的using(){}关键字,用来自动确保调用对象的dispose()方法,即使对象有异常抛出。C#中可以使用using{}的对象必须已经实现了IDispose接口。]

    复制代码
    def TestWith():
      with open(
    "myfile.txt") as f:
         
    for line in f:
             
    print (line)
      f.readline() 
    #f is already clean up here, here will meet ValueError exception
       
    TestWith()
    复制代码

    在with语句执行完以后,f对象马上就被释放了。所以下面在调用f.readline()会出错。

    二 with + try...except

    既能让对象自动释放,又包含了异常捕获的功能。

    复制代码
    class controlled_execution(object):
        
    def __init__(self, filename):
            self.filename 
    = filename
            self.f 
    = None

        
    def __enter__(self):
            
    try:
                f 
    = open(self.filename, 'r')
                content 
    = f.read()
                
    return content
            
    except IOError  as e:
                
    print (e)

        
    def __exit__(self, type, value, traceback):
            
    if self.f:
                
    print ('type:%s, value:%s, traceback:%s' % (str(type), str(value), str(traceback)))
                self.f.close()

    def TestWithAndException():
        with controlled_execution(
    "myfile.txt") as thing:
            
    if thing:
                
    print(thing)

    #TestWithAndException()
    复制代码

    参考:

    http://jianpx.javaeye.com/blog/505469

  • 相关阅读:
    蓝桥杯 大数定理
    蓝桥杯 密码发生器
    简单定时器的使用
    Eclipse中更改Project Explorer的字体
    列的别名修改
    ||拼接字符串
    SQL知识总结
    java 打开记事本
    报表使用分组
    js处理异步问题
  • 原文地址:https://www.cnblogs.com/DjangoBlog/p/3501861.html
Copyright © 2011-2022 走看看