类的使用——自定义with语句

Python笔记本
459 0

代码

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') #手动抛出错误

运行

最后更新 2019-09-30
评论 ( 0 )
评论已关闭