Python 装饰器

Python装饰器好呀,就在方法前面加个 @装饰名称 就可以在我们方法外面套用一整套流程,特别方便。就比如写了几个函数,突然发现这几个函数要增加一个运行时间,那么采用装饰器的方式就再方便不过了。

比如下面的函数

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

调用say_hello(),输出Hello!

我想看下这个函数运行用了多久

import time

def timing_decorator(func):
    """
    定义一个装饰器,用于测量函数的运行时间。
    
    参数:
    func (function): 被装饰的函数。
    
    返回:
    wrapper (function): 包装后的函数,包含时间测量逻辑。
    """
    def wrapper(*args, **kwargs):
        """
        包装函数,用于在调用原函数前后添加时间测量逻辑。
        
        参数:
        *args: 原函数的位置参数。
        **kwargs: 原函数的关键字参数。
        
        返回:
        result: 原函数的返回值。
        """
        start_time = time.time()  # 记录函数开始执行的时间
        result = func(*args, **kwargs)  # 调用原函数,并传入所有参数
        end_time = time.time()  # 记录函数结束执行的时间
        print(f"Function {func.__name__} took {end_time - start_time:.4f} seconds to execute.")  # 打印函数执行时间
        return result  # 返回原函数的返回值
    return wrapper  # 返回包装后的函数

在调用时只需要

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

就可以了
再次调用say_hello(),就输出下面样子。
Hello!
Function say_hello took 0.0000 seconds to execute.

装饰器可以在不修改原函数代码的情况下,动态地添加新的功能。

你可能感兴趣的:(python)