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,因为此时错误栈不为空
posted @ 2017-09-25 19:56  不变1024  阅读(102)  评论(0编辑  收藏  举报