1. __enter__和 __exit__
上下文管理器的行为由两个魔术方法决定:
- __enter__(self) - 定义上下文管理器在 with 语句创建的块的开头应该做什么。__enter__的返回值 绑定到 with 语句的目标,即 as 语句后面的名称。
- __exit__(self, exc_type, exc_value, exc_tb) 此方法在执行流离开 with 上下文时调用。如果发生异常,则exc_type、exc_value和 分别exc_tb保存异常类型、值和回溯信息。
In [1]: class MyContext:
...: def __enter__(self):
...: print('Entering my context')
...: return [1, 2, 3]
...: def __exit__(self, exc_type, exc_value, exc_tb):
...: print('Leaving my context')
...: print(exc_type, exc_value, exc_tb, sep='_____')
In [2]: with MyContext() as data:
...: print(data[0])
...:
Entering my context
1
Leaving my context
None_____None_____None
In [3]: with MyContext() as data:
...: