Skip to content

上下文管理器:with语句 ​

with语句 ​

python
# 自动关闭文件
with open('file.txt', 'r') as f:
    content = f.read()
# 文件自动关闭

自定义上下文管理器 ​

python
class Timer:
    def __enter__(self):
        self.start = time.time()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time.time()
        print(f"Time: {self.end - self.start:.2f}s")
        return False  # 不抑制异常

with Timer():
    time.sleep(1)

contextlib模块 ​

python
from contextlib import contextmanager

@contextmanager
def file_manager(filename, mode):
    f = open(filename, mode)
    try:
        yield f
    finally:
        f.close()

with file_manager('file.txt', 'r') as f:
    print(f.read())

练习 ​

  1. 实现数据库连接上下文管理器
  2. 使用@contextmanager装饰器
  3. 处理异常的上下文管理器

答案:第五章答案

下一节:资源管理模式

用心记录每一步成长