欢迎访问宙启技术站
智能推送

Python中的装饰器函数及其实用案例

发布时间:2023-07-02 15:28:36

装饰器是Python中一种特殊的函数,它可以修改其他函数的行为,并扩展其功能。装饰器函数接受一个被装饰的函数作为参数,并返回一个修改后的函数。在Python中,装饰器是基于语法糖的一种实现方式,它使用了@符号来标识装饰器。

在Python中,装饰器函数可以用于以下几种实用案例:

1. 日志记录

装饰器可以用于在函数执行前后打印日志。例如,可以创建一个装饰器函数,用于记录函数的执行时间和参数。可以使用time模块来计算函数的执行时间,并使用args和kwargs参数来记录函数的参数。

import time

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling function {func.__name__} with arguments {args} {kwargs}")
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} executed in {end_time - start_time} seconds")
        return result
    return wrapper

@log_decorator
def add(a, b):
    return a + b

result = add(3, 4)
print(result)

2. 权限验证

装饰器可以用于对需要权限验证的函数进行包装,以确保只有具有特定权限的用户可以执行函数。可以创建一个装饰器函数来检查用户的权限,并在权限不足时抛出异常。

def auth_decorator(func):
    def wrapper(*args, **kwargs):
        if not check_user_permission():
            raise Exception("Insufficient permissions")
        return func(*args, **kwargs)
    return wrapper

@auth_decorator
def delete_file(file_id):
    # 删除文件的逻辑
    pass

delete_file(123)

3. 缓存

装饰器可以用于对函数进行缓存,以提高函数的执行效率。可以创建一个装饰器函数来保存函数的返回值,以及函数的参数,下次执行函数时可直接返回缓存的结果。

def cache_decorator(func):
    cache = {}

    def wrapper(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key in cache:
            return cache[key]
        result = func(*args, **kwargs)
        cache[key] = result
        return result

    return wrapper

@cache_decorator
def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

result = fibonacci(10)
print(result)

4. 计时器

装饰器可以用于为函数添加计时器,以衡量函数的执行时间。可以创建一个装饰器函数来计算函数的执行时间,并将结果打印出来。

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"Function {func.__name__} executed in {end_time - start_time} seconds")
        return result
    return wrapper

@timer_decorator
def calculate_sum(n):
    return sum(range(n+1))

result = calculate_sum(100)
print(result)

总结来说,装饰器是Python中一种非常实用的功能,它可以用于修改函数的行为,并扩展函数的功能。装饰器函数可以用于日志记录、权限验证、缓存以及计时器等实用场景。使用装饰器可以提高代码的可复用性和可读性,同时减少代码的重复编写。