# 不用写 trywith open('name.txt') as f: for i in f: print(i)
class TestWith: def __enter__(self): print('enter') def __exit__(self, exc_type, exc_val, exc_tb): print('exit')with TestWith(): print('Test is running')# 输出enterTest is runningexit
class TestWith: def __enter__(self): print('enter') def __exit__(self, exc_type, exc_val, exc_tb): if exc_tb is None: print('normal exit') else: print('err: %s' % exc_tb)# 可以想像成 with 包裹了 TestWith 对象,# 如果在运行中产生异常, 那么异常会传递给对象.with TestWith(): print('Test is running') # 手动抛出异常 raise NameError('testNameError')# 输出enterTest is runningerr: <traceback object at 0x7fe36e8614c0>Traceback (most recent call last): File "/home/jdxj/workspace/study-python/with.py", line 15, in <module> raise NameError('testNameError')NameError: testNameError