代码

In [2]: class Testwith():
   ...:     def __enter__(self):
   ...:         print("run")
   ...:     def __exit__(self, exc_type, exc_val, ext_tb):
   ...:         print('exit')
   ...:         

In [3]: with Testwith():
   ...:     print('Test is runing')

运行

with处理异常错误

代码

class Testwith():
    def __enter__(self):
        print("run")
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_tb is None:
            print('正常结束')
        else:
            print('has error :%s' %exc_tb)

with Testwith():
    print("Test is runing")
    raise NameError('testNameError') #手动抛出错误

运行

文章名: 《类的使用——自定义with语句》

本文链接:https://lula.fun/968.html

除特别注明外,文章均由 噜啦 原创

 原创文章 转载时请注明 出处 以及文章链接
最后修改:2019 年 09 月 30 日 12 : 05 AM