Loading
Avalon World
0%
INITIALIZING
DOC_ID // 4124d6ONLINE

Python 装饰器与上下文管理器深度解析

2026-11-9
UPDATED: 2026-11-8
PYTHON
2206 CHARS
#开发
Avalon
温馨提醒

这篇文章最后更新于 20 天前,内容可能已过时,请谨慎参考。

WARN // STALE
🐍
装饰器与上下文管理器是 Python 的两大"语法糖"——前者让你在不修改原函数代码的前提下增强功能,后者让你优雅地管理资源(文件、锁、数据库连接)。它们的底层都是可调用对象协议与上下文协议,理解这两个协议,你就掌握了 Python 元编程的半壁江山。

一、装饰器:从函数到高阶函数

1.1 函数也是对象

理解装饰器的前提:函数是 first-class 对象,可以赋值、传参、返回。
def greet(name): return f"Hello, {name}!" # 函数名本身是引用 print(greet) # <function greet at 0x...> print(greet.__name__) # greet # 函数可以赋值给变量 say_hello = greet print(say_hello("World")) # Hello, World! # 函数可以作为参数传入 def call_twice(fn, arg): return fn(arg) + " " + fn(arg) print(call_twice(greet, "Python")) # Hello, Python! Hello, Python! # 函数可以作为返回值 def make_multiplier(factor): def multiplier(x): return x * factor return multiplier double = make_multiplier(2) print(double(5)) # 10
🔸 关键点:Python 中一切皆对象,函数也不例外。greet 既是函数名,也是指向函数对象的引用。

1.2 最简单的装饰器

装饰器本质上是一个接受函数、返回函数的高阶函数:
def my_decorator(fn): def wrapper(*args, **kwargs): print("函数调用前") result = fn(*args, **kwargs) print("函数调用后") return result return wrapper @my_decorator def add(a, b): return a + b print(add(3, 5)) # 函数调用前 # 函数调用后 # 8
@my_decorator 等价于 add = my_decorator(add)。装饰器在函数定义时立即执行,而非调用时。

1.3 带参数的装饰器

如果装饰器本身也需要参数,需要三层嵌套:
def repeat(times): """外层:接收装饰器参数""" def decorator(fn): """中层:接收被装饰函数""" def wrapper(*args, **kwargs): """内层:实际执行逻辑""" for _ in range(times): result = fn(*args, **kwargs) return result return wrapper return decorator @repeat(times=3) def say_hello(name): print(f"Hello, {name}!") say_hello("Python") # Hello, Python! # Hello, Python! # Hello, Python!

1.4 functools.wraps:保留元信息

装饰器会覆盖原函数的 __name__、__doc__ 等元信息,用 functools.wraps 保留:
from functools import wraps def timer(fn): @wraps(fn) # 把原函数的元信息复制到 wrapper def wrapper(*args, **kwargs): import time start = time.perf_counter() result = fn(*args, **kwargs) end = time.perf_counter() print(f"{fn.__name__} 耗时 {end - start:.4f}s") return result return wrapper @timer def slow_function(): """模拟一个慢函数""" import time time.sleep(0.1) print(slow_function.__name__) # slow_function(不加 wraps 会变成 wrapper) print(slow_function.__doc__) # 模拟一个慢函数

二、内置装饰器与常用场景

2.1 @staticmethod / @classmethod

类中的静态方法与类方法:
class MathUtils: @staticmethod def add(a, b): """静态方法:不依赖实例或类""" return a + b @classmethod def from_dict(cls, data): """类方法:接收类作为第一个参数""" return cls(**data) print(MathUtils.add(3, 5)) # 8(无需实例化) obj = MathUtils.from_dict({"x": 1, "y": 2})

2.2 @property:属性装饰器

把方法变成属性访问,实现 getter/setter:
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): """getter""" return self._radius @radius.setter def radius(self, value): """setter""" if value < 0: raise ValueError("半径不能为负") self._radius = value @property def area(self): """只读属性""" import math return math.pi * self._radius ** 2 c = Circle(5) print(c.area) # 78.5398...(无需括号) c.radius = 10 # 触发 setter print(c.area) # 314.1592...

2.3 @functools.lru_cache:缓存

自动缓存函数结果,适合计算密集型场景:
from functools import lru_cache @lru_cache(maxsize=128) def fibonacci(n): """带缓存的斐波那契数列""" if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(30)) # 832040(首次计算,后续直接返回缓存)

2.4 @contextlib.contextmanager

把生成器变成上下文管理器(详见第三节):
from contextlib import contextmanager @contextmanager def timer(name): import time start = time.perf_counter() yield end = time.perf_counter() print(f"{name} 耗时 {end - start:.4f}s") with timer("测试"): sum(range(1000000))

三、上下文管理器:资源管理的优雅解

3.1 为什么需要上下文管理器?

对比传统写法与上下文管理器:
# 传统写法:容易忘记关闭 f = open("data.txt", "r") try: content = f.read() # 处理数据... finally: f.close() # 必须显式关闭 # 上下文管理器:自动关闭 with open("data.txt", "r") as f: content = f.read() # 退出 with 块时自动调用 f.close()

3.2 实现上下文管理器:两种方式

方式一:类实现 __enter__ / __exit__

class DatabaseConnection: def __init__(self, db_url): self.db_url = db_url self.conn = None def __enter__(self): """进入 with 块时调用,返回值赋给 as 后的变量""" self.conn = connect(self.db_url) return self.conn def __exit__(self, exc_type, exc_val, exc_tb): """退出 with 块时调用,无论是否异常""" if self.conn: self.conn.close() # 返回 True 则异常被吞掉,False 则异常继续传播 return False with DatabaseConnection("postgresql://localhost/mydb") as db: db.execute("SELECT * FROM users")

方式二:@contextlib.contextmanager 装饰器

from contextlib import contextmanager @contextmanager def database_connection(db_url): conn = connect(db_url) try: yield conn # 进入 with 块时返回连接 finally: conn.close() # 退出 with 块时自动关闭 with database_connection("postgresql://localhost/mydb") as db: db.execute("SELECT * FROM users")

3.3 __exit__ 参数详解

__exit__ 接收三个异常信息参数:
class SafeDivision: def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is ZeroDivisionError: print(f"捕获除零异常:{exc_val}") return True # 吞掉异常,程序继续 return False # 其他异常继续传播 with SafeDivision(): result = 1 / 0 # 被捕获,不崩溃 print("程序继续执行") # 这行会输出

四、装饰器与上下文管理器的组合

4.1 装饰器 + 上下文管理器:计时器

from functools import wraps from contextlib import contextmanager import time def timed(fn): @wraps(fn) def wrapper(*args, **kwargs): with timer(fn.__name__): return fn(*args, **kwargs) return wrapper @contextmanager def timer(name): start = time.perf_counter() yield end = time.perf_counter() print(f"{name} 耗时 {end - start:.4f}s") @timed def slow_function(): time.sleep(0.1) slow_function() # slow_function 耗时 0.1002s

4.2 单例模式:装饰器实现

from functools import wraps def singleton(cls): """类装饰器:单例模式""" instances = {} @wraps(cls) def wrapper(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return wrapper @singleton class Database: def __init__(self): print("初始化数据库连接") db1 = Database() # 初始化数据库连接 db2 = Database() # 无输出,返回同一实例 print(db1 is db2) # True

4.3 重试装饰器

import time from functools import wraps def retry(max_attempts=3, delay=1, exceptions=(Exception,)): """重试装饰器:失败时自动重试""" def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): for attempt in range(max_attempts): try: return fn(*args, **kwargs) except exceptions as e: if attempt == max_attempts - 1: raise print(f"第 {attempt + 1} 次失败,{delay}s 后重试...") time.sleep(delay) return wrapper return decorator @retry(max_attempts=3, delay=0.5, exceptions=(ConnectionError,)) def fetch_data(url): """模拟网络请求""" raise ConnectionError("网络不通") # fetch_data("https://api.example.com") # 重试 3 次后抛出异常

五、常见陷阱与最佳实践

5.1 装饰器执行时机

装饰器在函数定义时立即执行,而非调用时:
def my_decorator(fn): print("装饰器执行!") return fn @my_decorator def my_function(): pass # 输出:装饰器执行!(模块导入时就执行了)

5.2 装饰器堆叠顺序

多个装饰器时,从下往上应用:
def decorator1(fn): print("decorator1") def wrapper(): print("before 1") fn() print("after 1") return wrapper def decorator2(fn): print("decorator2") def wrapper(): print("before 2") fn() print("after 2") return wrapper @decorator1 @decorator2 def hello(): print("hello") # 等价于:hello = decorator1(decorator2(hello)) # 输出顺序:decorator2 → decorator1 → before 1 → before 2 → hello → after 2 → after 1

5.3 闭包陷阱:延迟绑定

循环中创建装饰器时,变量是延迟绑定的:
# ❌ 错误:所有函数都返回 9 funcs = [] for i in range(3): def f(): return i * 2 funcs.append(f) print([f() for f in funcs]) # [18, 18, 18](i 最终是 3) # ✅ 正确:用默认参数捕获当前值 funcs = [] for i in range(3): def f(i=i): return i * 2 funcs.append(f) print([f() for f in funcs]) # [0, 2, 4]

5.4 类装饰器 vs 函数装饰器

类装饰器可以维护状态,实现更复杂的逻辑:
class Counter: """类装饰器:统计函数调用次数""" def __init__(self, fn): self.fn = fn self.count = 0 wraps(fn)(self) def __call__(self, *args, **kwargs): self.count += 1 print(f"第 {self.count} 次调用") return self.fn(*args, **kwargs) @Counter def greet(name): return f"Hello, {name}!" print(greet("Alice")) # 第 1 次调用 print(greet("Bob")) # 第 2 次调用 print(greet.count) # 2(可以直接访问状态)

六、性能基准测试

import timeit from functools import lru_cache # 装饰器缓存 vs 无缓存 @lru_cache(maxsize=128) def cached_fib(n): if n < 2: return n return cached_fib(n - 1) + cached_fib(n - 2) def fib(n): if n < 2: return n return fib(n - 1) + fib(n - 2) # 首次计算(缓存未命中) cached_time = timeit.timeit(lambda: cached_fib(30), number=100) raw_time = timeit.timeit(lambda: fib(30), number=100) print(f"缓存版 100 次: {cached_time:.4f}s") print(f"无缓存 100 次: {raw_time:.4f}s") print(f"缓存快 {raw_time / cached_time:.1f} 倍") # 缓存命中后 cached_time2 = timeit.timeit(lambda: cached_fib(30), number=1000) print(f"缓存命中后 1000 次: {cached_time2:.4f}s")

七、总结

特性
装饰器
上下文管理器
核心协议
可调用对象(__call__)
__enter__ / __exit__
语法
@decorator
with context as x:
执行时机
函数定义时
进入/退出 with 块时
主要用途
增强函数功能
管理资源生命周期
典型场景
缓存、日志、权限校验
文件、锁、数据库连接
核心要点:
  1. 装饰器 = 高阶函数 + 闭包,本质是"函数的函数"
  1. functools.wraps 保留原函数元信息,生产环境必加
  1. 上下文管理器用 __enter__/__exit__ 或 @contextmanager 实现
  1. __exit__ 返回 True 可吞掉异常,实现"优雅降级"
  1. 装饰器堆叠从下往上应用,注意执行顺序
  1. 循环中创建闭包用默认参数捕获当前值,避免延迟绑定陷阱

📚 参考资料:
NAVIGATION // Related Articles