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

    一 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

  • 相关阅读:
    68.css 3d 卡片翻转效果
    67.canvas绘制常规图形
    66.环形加载动画(canvas/svg)
    65.canvas画一个表(2)
    64.canvas画一个表(1)
    63.实现一个拖拽排序
    62.textarea 自适应高度
    co co a P o a d s的使用
    在MJRefresh的基础上实现动画的自定义和自动下拉刷新
    iOS26 AFNetworking
  • 原文地址:https://www.cnblogs.com/itech/p/1934779.html
Copyright © 2011-2022 走看看