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
  • 相关阅读:
    全景拼接
    krpano之字幕添加
    UML之时序图
    krpano之语音介绍
    小工具之录音(文字转语音)
    动态生成按钮的点击事件绑定
    登录之简单验证码
    登录之md5加密
    redis与mysql数据同步
    Sql Server 主从数据库配置
  • 原文地址:https://www.cnblogs.com/lq1024/p/7593646.html
Copyright © 2011-2022 走看看