首先写一个简单的异常处理
try:
f = open('demo.txt', 'w')
# 抛出异常
raise TypeError
# 捕获异常
except TypeError as e:
print('TypeError')
f.close()
except ValueError as e:
print('ValueError')
f.close()
except Exception as e:
print('Exception')
f.close()
finally:
print('end...')
# TypeError
# end...
使用上下文管理器的目的就是简化以上的操作
with open(‘demo.txt’, ‘w’) as f:
f.write()
那类可以支持上下文管理器吗?
class Sample(object):
def __enter__(self):
print('Start')
return self
def demo(self):
print('Sample...')
def __exit__(self, exc_type, exc_val, exc_tb):
print(exc_type) # 异常类 <class 'AttributeError'>
print(exc_val) # 异常值 'Sample' object has no attribute 'demos'
print(exc_tb) # 追踪信息,也就是在哪一行报错 <traceback object at 0x000002098C398208>
print('ending')
with Sample() as sample:
sample.demos()
想要类支持上下文管理器必须要有__enter__和__exit__方法
还有一种更简单的上下文管理器,通过修饰器
import contextlib
@contextlib.contextmanager
def text(name):
print('Start...')
yield {}
print('Ending...')
# yield 上面的相当于__enter__函数,下面相当于__exit__函数
with text('juren') as f:
print('operation')
# Start...
# operation
# Ending...