Skip to content

Decorator

一句话解释

decorator 是 函数 那个 takes another 函数 and 返回 修改 version, applied 使用 @ 语法.

用大白话说

decorator 是函数那个 wraps another 函数, 添加 behavior 之前 or 之后原始函数运行. 你 apply 它使用 @decorator_name syntax above a function definition.

Decorators are useful for cross-cutting concerns: logging, timing, caching, access control, input validation. Instead of repeating this code in every function, you write it once as a decorator and apply it where needed.

A decorator takes a function as input and returns a new function (the wrapper). The wrapper calls the original function and adds extra behavior. Decorators can also accept arguments by using a decorator factory.

示例

python
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_calls
def add(a, b):
    return a + b

add(3, 5)
# Prints: Calling add
# Prints: add returned 8

Decorators wrap 函数 到 添加 behavior. @ 语法 applies 它们. wrapper calls 原始 and 添加 extra logic.

常见混淆

  • 容易混淆的对象: 闭包

    关键区别: decorator 是 函数 那个 修改 another 函数. 闭包 是 函数 那个 captures 变量 从 它的 enclosing 作用域. Decorators 经常 use 闭包 (wrapper 是 闭包), 但 它们 是 不同 概念.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表