类的使用——自定义with语句
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')
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') #手动抛出错误