zoukankan      html  css  js  c++  java
  • python中with学习

    python中with是非常强大的一个管理器,我个人的理解就是,我们可以通过在我们的类里面自定义enter(self)和exit(self,err_type,err_value,err_tb)这两个内置函数,然后通过with使用我们的这两个函数
    enter(self):这个内置函数是运行这个对象之前调用的函数
    exit(self,err_type,err_value,err_tb):这个内置函数是运行结束后调用的函数,上代码:

    #coding=utf-8
    class a():
        def __init__(self):
            print 'init'
        def __enter__(self):
            print int(reduce(lambda x,y:x*y,range(2,4)))
            print '_______________________________'
        def __exit__(self, exc_type, exc_value, exc_tb):#参数代表:错误类型,错误内容,错误栈(个人俗称)
            if exc_tb is None:  #如果错误栈为空,代表正常运行
                print 'free exit'
            else:
                print 'direct exit'
    with a():
        print "11111111"
    #输出:
    #init
    #6
    #_______________________________
    #11111111
    #free exit
    #可以看出输出1111111前调用了__enter__里面的函数,执行完之后退出时调用了__exit__函数

    修改如下:

    with a():
        print "11111111"
        raise TypeError
    #输出
    #init
    #6
    #_______________________________
    #11111111
    #direct exit
    #Traceback (most recent call last):
    #  File "with.py", line 15, in <module>
    #    raise TypeError
    #TypeError
    #可以看到当有错误发生时,程序会输出TypeError,因为此时错误栈不为空
    
    欢迎来邮件交流:lq65535@163.com
  • 相关阅读:
    HDU 1010 Tempter of the Bone
    HDU 4421 Bit Magic(奇葩式解法)
    HDU 2614 Beat 深搜DFS
    HDU 1495 非常可乐 BFS 搜索
    Road to Cinema
    Sea Battle
    Interview with Oleg
    Spotlights
    Substring
    Dominating Patterns
  • 原文地址:https://www.cnblogs.com/lq1024/p/7593646.html
Copyright © 2011-2022 走看看