Python同步上下文管理器
__enter__ 的返回值会绑定到 as 子句的变量
举例如下:
python
class MyContext:
def __enter__(self):
print("进入上下文,返回一个字符串")
return "Hello, World!" # 这个返回值会绑定到 as 后面的变量
def __exit__(self, exc_type, exc_val, exc_tb):
print("退出上下文")
return False
with MyContext() as value:
print(f"在 with 块内,value = {value}")
输出结果如下:
text
进入上下文,返回一个字符串 在 with 块内,value = Hello, World! 退出上下文
