classMyContext: def__enter__(self): print("Entering the context") return self
def__exit__(self, exc_type, exc_value, traceback): """ exc_type: 异常类型,如果没有异常则为None exc_value: 异常值,如果没有异常则为None traceback: 追溯信息,如果没有异常则为None """ print("Exiting the context") if exc_type isnotNone: print(f"An exception of type {exc_type} occurred with value {exc_value}") returnFalse# Return True if you want to suppress the exception
# 使用with语句创建上下文管理器 with MyContext() as context: print("Inside the context")
print("Outside the context")
输出
1 2 3 4
Entering the context Inside the context Exiting the context Outside the context