通常来说,实现上下文管理器,需要编写一个带有__enter__和 __exit__的类,类似这样: class ListTransaction: def __init__(self, orig_list): self.orig_list = orig_list self.working = list(orig_list) def __enter__(self): return self.working def __exit__(self, exc_type, exc_val, exc_tb):…