Python 装饰器

Python 装饰器

装饰器原理

  1. 定义
    1. 本质是函数,用来装饰其他函数,为其他函数添加附加功能
  2. 原则
    1. 不能修改被装饰函数的源代码
    2. 不能修改被装饰的函数的调用方式
  3. 实现装饰器知识储备
    1. 函数就是变量
    2. 高阶函数
      1. 把一个函数当作实参传给另外一个函数,在不修改被装饰函数源代码情况下为其添加功能
      2. 返回值中包含函数名,不修改函数的调用方式
    3. 嵌套函数
      1. 高阶函数 + 嵌套函数 → 装饰器

举个例子

import time
from datetime import datetime


# 定义一个装饰器函数
def measure_time(func):
    
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        execution_time = end_time - start_time
        print(f"{func.__name__} 函数的执行时间为: {execution_time:.4f} 秒")
        return result

    return wrapper


# 使用装饰器来测量函数执行时间
@measure_time
def now():
    # 打印当前时间
    time.sleep(2)
    currentDateAndTime = datetime.now()
    currentTime = currentDateAndTime.strftime("%H:%M:%S")
    print("The current time is", currentTime)


if __name__ == '__main__':
    # 调用 now
    now()

posted @   Lockegogo  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示