skip to content
Liu Yang's Blog

[Python] Python装饰器(Decorator)简介与示例

/ 3 min read

Table of Contents

Python 装饰器(Decorator)简介与示例

装饰器本质上是一个高阶函数

接受一个函数作为参数,返回一个对该函数进行“包裹(wrapper)”后的新函数。

通过这种方式,我们可以在不修改原函数代码的前提下,对其行为进行增强或修改。


装饰器的基本结构

def decorator(func):
def wrapper(*args, **kwargs):
# 在原函数执行前做一些事情
result = func(*args, **kwargs)
# 在原函数执行后做一些事情
return result
return wrapper

当使用 @decorator 语法时,等价于:

func = decorator(func)

保留函数元信息:functools.wraps

由于装饰器返回的是 wrapper 函数, 被装饰函数的元信息(如 __name____doc__)会被覆盖

为了解决这个问题,Python 提供了 functools.wraps,用于将原函数的元信息复制到 wrapper 上。


示例:日志装饰器

import functools
def log_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"函数 {func.__name__} 开始执行...")
result = func(*args, **kwargs)
print(f"函数 {func.__name__} 执行完毕。")
return result
return wrapper
@log_decorator
def say_hello(name):
"""向用户打招呼"""
print(f"Hello, {name}!")
say_hello("World")

输出结果:

函数 say_hello 开始执行...
Hello, World!
函数 say_hello 执行完毕。

此时:

say_hello.__name__ # 'say_hello'
say_hello.__doc__ # '向用户打招呼'

使用场景与思想

装饰器常用于实现横切关注点(Cross-Cutting Concerns),例如:

  • 日志打印
  • 执行时间统计
  • 权限校验 / 鉴权
  • 缓存
  • 重试机制

从设计思想上看,装饰器体现了**面向切面编程(AOP)**的理念,与 Java Spring 中的 AOP 在思想上高度一致。


小结

  • 装饰器 = 高阶函数 + 闭包
  • @decorator 是语法糖
  • functools.wraps 用于保留函数元信息
  • 本质是对函数调用过程的代理和增强