一切皆函数

Python 里函数可以:赋值给变量、作为参数传给另一个函数、作为返回值。这是装饰器能工作的基础。

def hello():
    print("hi")

f = hello    # 函数赋值给变量
f()          # 调用 f 就是调用 hello

def my_decorator(func):
    def wrapper():
        print("调用前")
        func()
        print("调用后")
    return wrapper

def say_hello():
    print("Hello!")

say_hello = my_decorator(say_hello)
say_hello()
# 输出:调用前 / Hello! / 调用后

@ 语法糖

@my_decorator 就是 say_hello = my_decorator(say_hello) 的简写。

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

带参数的装饰器

import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} 耗时 {time.time()-start:.3f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

slow_function()
# 输出:slow_function 耗时 1.001s

实际应用

装饰器作用
@login_required检查用户是否登录(Web 框架常用)
@cache / @lru_cache缓存函数结果,避免重复计算
@property把方法变成属性调用
@staticmethod静态方法
@dataclass自动生成 __init__ 等方法
本质:装饰器就是"接收函数、返回新函数"的高阶函数。@ 只是语法糖,让代码更干净。