当前位置:首页>python>Part 3:Python 装饰器

Part 3:Python 装饰器

  • 2026-10-11 07:05:27
Part 3:Python 装饰器

装饰器 Decorators

Python 中的函数可以赋值给变量,可以作为参数传递给另一个函数,可以作为函数的返回值。

于是装饰器就出现了。

装饰器的本质就是在不改变一个函数代码的前提下,为该函数增添额外的功能。

from types import FunctionTypedefmy_decorator(func: FunctionType = lambda: print("default function")) -> FunctionType:# 类型注解,期望传入一个函数类型的参数 func, 并且使用 lambda 匿名函数赋了一个默认值,期望返回一个函数defwrapper():# 内层函数,拓展 func 的功能        print("before")        func()        print("after")return wrapper  # 将内层函数返回defsay_hello():    print("Hello")say_hello = my_decorator(say_hello)  # 将 say_hello 函数作为参数传入 my_decorator() 函数say_hello()

在上面的案例中,say_hello 函数在定义的时候,只有一个打印 "Hello" 的功能。后面将 say_hello 函数作为参数传递给 my_decorator 函数,并将其包裹在一个内层嵌套的函数 wrapper 中,前后添加了更多打印功能,并将函数返回重新赋值给 say_hello 变量,最后调用 say_hello() 函数,于是原来的 say_hello 函数就有了更多的打印功能。运行:

beforeHelloafter

@ 语法糖

@ 语法糖的出现只是为了让装饰器写法上更加简洁。

@my_decoratordefsay_hello():    print("Hello")# @ 语法糖让 say_hello 函数在定义的时候就作为参数传递给 my_decorator 立即扩展其功能并返回# 无需再写say_hello = my_decorator(say_hello)say_hello()

装饰器的执行时机:

defdecorator(func):    print(f"装饰器被调用,正在装饰 {func.__name__}")defwrapper(*args, **kwargs):return func(*args, **kwargs)return wrapper@decoratordefmy_function():    print("函数执行")print("--- 函数定义完成 ---")my_function()# 输出:# 装饰器被调用,正在装饰 my_function# --- 函数定义完成 ---# 函数执行

应用:计算调用一个函数的运行时间

import timedeftimer(func):"""装饰器:计算函数执行时间"""defwrapper():        start = time.time()        result = func()        print(f"{func.__name__} 耗时: {time.time() - start:.4f}秒")return resultreturn wrapper@timerdefsay_hello():    print("Hello!")    time.sleep(1)    print("World!")@timerdefsay_goodbye():    print("Goodbye!")    time.sleep(0.5)    print("See you!")# 使用say_hello()  # 自动计时say_goodbye()  # 自动计时

闭包 Closure

闭包是装饰器的灵魂。

闭包:内部函数记住了外部函数的变量,即使外部函数已经执行完毕。

defouter(x):definner(y):return x + y  # inner 记住了 outer 的参数 xreturn inneradd_5 = outer(5) # 调用 outer, 将内部函数 inner 赋值给 add_5print(add_5(3))  # 8 (5 + 3)print(add_5(10))  # 15 (5 + 10)

闭包的条件:

  1. 嵌套函数(函数内部定义函数)
  2. 内部函数引用外部函数的变量
  3. 外部函数返回内部函数

处理带参数函数

内层函数使用可变位置参数 *args 和可变关键字参数 *kwargs 来接收被装饰函数的参数:

defdecorator(func):defwrapper(*args, **kwargs):# 万能参数        print(f"调用函数: {func.__name__}")        print(f"参数: args={args}, kwargs={kwargs}")        result = func(*args, **kwargs)        print(f"返回值: {result}")return resultreturn wrapper@decoratordefadd(a, b):return a + b@decoratordefgreet(name, greeting="Hello"):returnf"{greeting}, {name}"add(3, 5)greet("Alice", greeting="Hi")

多装饰器的执行顺序

defdecorator_a(func):    print("装饰器A执行")defwrapper(*args, **kwargs):        print("A 前")        result = func(*args, **kwargs)        print("A 后")return resultreturn wrapperdefdecorator_b(func):    print("装饰器B执行")defwrapper(*args, **kwargs):        print("B 前")        result = func(*args, **kwargs)        print("B 后")return resultreturn wrapper@decorator_a@decorator_bdeftest():    print("核心功能")test()

执行:

装饰器B执行装饰器A执行A 前B 前核心功能B 后A 后

多装饰器函数的定义阶段,执行顺序是由内而外,离被装饰函数最近的装饰器先执行,执行顺序往外层层递减。

@decorator_a@decorator_bdeftest():    print("核心功能")# 以上代码相当于test = decorator_a(decorator_b(test))

在被装饰函数的调用阶段 test(),最外层的装饰器代码先执行,由外而内执行装饰器的内层函数代码。

带参数的装饰器

# 控制重试次数@retry(times=3)defunstable_api():    ...# 指定日志级别@log(level="DEBUG")defprocess_data():    ...

实现 —— 使用三层嵌套

defrepeat(times):"""带参数的装饰器:重复执行次数"""defdecorator(func):defwrapper(*args, **kwargs):for i in range(times):                print(f"第 {i + 1} 次执行")                func(*args, **kwargs)return wrapperreturn decorator@repeat(times=3)defsay_hello(name):    print(f"Hello {name}")say_hello("Jackey")# 等价于:# say_hello = repeat(3)(say_hello)

repeat() 层接收装饰器参数,decorator 层接收被装饰函数,wrapper 层接收被装饰函数的参数并为被装饰函数添加额外功能。

灵活的日志装饰器:

import loggingdeflog(level="INFO", prefix="[APP]"):"""带参数的日志装饰器"""defdecorator(func):defwrapper(*args, **kwargs):            log_msg = f"{prefix} 调用 {func.__name__}"if level == "INFO":                logging.info(log_msg)elif level == "DEBUG":                logging.debug(log_msg)elif level == "ERROR":                logging.error(log_msg)return func(*args, **kwargs)return wrapperreturn decorator@log(level="DEBUG", prefix="[API]")deffetch_data():    print("获取数据...")fetch_data()

类装饰器

使用类实现装饰器(__call__方法:可以让类的实例像函数一样被调用)

classCountCalls:"""类装饰器:统计函数调用次数"""def__init__(self, func):        self.func = func        self.count = 0def__call__(self, *args, **kwargs):        self.count += 1        print(f"第 {self.count} 次调用 {self.func.__name__}")return self.func(*args, **kwargs)@CountCallsdefsay_hello():    print("Hello!")# 相当于 say_hello = CountCalls(say_hello)say_hello()say_hello()say_hello()

执行:

第 1 次调用 say_helloHello!第 2 次调用 say_helloHello!第 3 次调用 say_helloHello!

类装饰器的优势:

  1. 保持状态:可以在实例属性中保存数据

  2. 更清晰的接口:适合复杂的装饰器

  3. 便于测试:可以 mock 装饰器实例

    classMyDecorator:def__init__(self, func):        self.func = func        self.cnt = 0def__call__(self, *args, **kwargs):        self.cnt += 1        print(f"调用次数:{self.cnt}")return self.func(*args, **kwargs)@MyDecoratordefwork():return"完成任务"

    正常运行 work() 会自动计数、打印日志。

    现在写单元测试,我们不想要计数、打印逻辑,只想测试 work 原本的业务逻辑:

    from unittest.mock import MagicMock# work 是 MyDecorator 实例# 直接替换实例的 __call__ 方法(mock实例行为)original_func = work.funcwork.__call__ = MagicMock(return_value=original_func())print(work())# 不会执行装饰器里 self.cnt +=1 和print,装饰逻辑被屏蔽

装饰器链与嵌套

上文提到的多装饰器:

import timedeftimer(func):defwrapper(*args, **kwargs):        start = time.time()        result = func(*args, **kwargs)        print(f"⏱️ {func.__name__} 耗时: {time.time()-start:.4f}s")return resultreturn wrapperdeflog(func):defwrapper(*args, **kwargs):        print(f"📝 调用 {func.__name__} 参数: {args}")        result = func(*args, **kwargs)        print(f"📝 {func.__name__} 返回: {result}")return resultreturn wrapper@timer@logdefadd(a, b):    time.sleep(0.1)return a + badd(3, 5)

装饰器工厂组合:

defcompose(*decorators):"""组合多个装饰器"""defapply(func):for decorator in reversed(decorators):            func = decorator(func)return funcreturn apply# 使用@compose(timer, log)defmultiply(a, b):return a * b

使用 functools.wraps 保留函数的元数据

普通装饰器:

defdecorator(func):defwrapper(*args, **kwargs):return func(*args, **kwargs)return wrapper@decoratordefmy_function():"""这是文档字符串"""passprint(my_function.__name__)    # wrapper(不是 my_function!)print(my_function.__doc__)     # None(文档丢失!)

解决方案:使用 functools.wraps :

from functools import wrapsdefdecorator(func):    @wraps(func)  # 关键!defwrapper(*args, **kwargs):return func(*args, **kwargs)return wrapper@decoratordefmy_function():"""这是文档字符串"""passprint(my_function.__name__)    # my_functionprint(my_function.__doc__)     # 这是文档字符串

@wraps 复制了这些属性:

  • __name__
  • __doc__
  • __module__
  • __annotations__
  • __dict__

最佳实践:始终使用 @wraps 装饰所有装饰器的 wrapper 函数。




最新文章

随机文章