带参数的Python装饰器原来这么简单,5分钟彻底掌握!

带参数的装饰器(三层嵌套结构)

python 复制代码
def repeat_execution(n_times):
    # 第一层:接收装饰器参数
    def decorator(func):
        # 第二层:接收被装饰函数
        def wrapper(*args, **kwargs):
            # 第三层:执行装饰逻辑
            for _ in range(n_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat_execution(n_times=3)
def say_hello(name):
    print(f"Hello, {name}!")

say_hello("Alice")

输出:

复制代码
Hello, Alice!
Hello, Alice!
Hello, Alice!

深度解析:装饰器参数如何传递

  1. @repeat_execution(n_times=3) 首先执行
    • 调用repeat_execution(3)返回decorator函数
  2. 接着执行@decorator
    • say_hello作为参数传递给decorator
  3. 最终生成装饰后的wrapper函数

带状态记录的装饰器

python 复制代码
def log_performance(metric_name):
    def decorator(func):
        func.call_count = 0  # 添加函数属性
        
        def wrapper(*args, **kwargs):
            func.call_count += 1
            print(f"[{metric_name}] 执行 #{func.call_count}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@log_performance("用户验证")
def authenticate(user):
    return user == "admin"

print(authenticate("guest"))
print(authenticate("admin"))
print(f"验证函数调用次数: {authenticate.call_count}")

输出:

ini 复制代码
[用户验证] 执行 #1
False
[用户验证] 执行 #2
True
验证函数调用次数: 2

类实现的装饰器参数

python 复制代码
class TimeoutRetry:
    def __init__(self, retries=3, delay=1):
        self.retries = retries
        self.delay = delay
    
    def __call__(self, func):
        import time
        def wrapper(*args, **kwargs):
            for attempt in range(self.retries):
                try:
                    return func(*args, **kwargs)
                except TimeoutError:
                    print(f"超时重试中... ({attempt+1}/{self.retries})")
                    time.sleep(self.delay)
            raise Exception("所有重试均失败")
        return wrapper

@TimeoutRetry(retries=2, delay=0.5)
def fetch_data():
    # 模拟网络请求
    raise TimeoutError("连接超时")

fetch_data()  # 将触发重试机制

装饰器参数的最佳实践

  1. 命名规范 :使用描述性的参数名(如max_retries而非n

  2. 参数验证 :在装饰器最外层验证参数有效性

    python 复制代码
    def validate_params(max_time):
        if max_time <= 0:
            raise ValueError("最大时间必须为正数")
  3. 保留元数据 :使用@functools.wraps保持原始函数属性

    python 复制代码
    from functools import wraps
    
    def debug_decorator(level):
        def decorator(func):
            @wraps(func)  # 保留原始函数信息
            def wrapper(*args, **kwargs):
                if level > 1:
                    print(f"[DEBUG] 调用 {func.__name__}")
                return func(*args, **kwargs)
            return wrapper
        return decorator
相关推荐
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
ValhallaCoder1 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
崔庆才丨静觅1 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
猫头虎2 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端