上下文管理協議其實就是with Foo() as f:類似這種寫法
class Foo:
def __init__(self,name):
self.name=name
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
print(exc_type)
print(exc_val)
print(exc_tb)
return True
with Foo('a.txt') as f:
print('ok')
print('-----------end----------')
用with這種寫法的最大好處就是不用寫f.close()了。