Python装饰器实战指南

Python装饰器实战指南

Python装饰器是一种强大的语法特性,可以在不修改函数代码的情况下增强函数功能。

1. 基础装饰器

最简单的装饰器就是一个接受函数并返回新函数的高阶函数:

复制代码
def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time()-start:.2f}s")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(1)
    return "done"

2. 带参数的装饰器

如果装饰器本身需要参数,就需要再嵌套一层函数:

复制代码
def retry(max_attempts=3):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    if i == max_attempts - 1:
                        raise
                    print(f"Attempt {i+1} failed: {e}")
        return wrapper
    return decorator

3. 实际应用场景

  • 权限校验:在Web开发中检查用户是否登录
  • 缓存:对耗时函数的结果进行缓存
  • 日志:自动记录函数调用和参数
  • 重试:对可能失败的操作自动重试

掌握装饰器是Python进阶的关键一步,建议多加练习。

相关推荐
星云穿梭8 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵8 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠14 小时前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780511 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠2 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3102 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫2 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试