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

Python装饰器函数的作用和应用

发布时间:2023-07-29 01:15:41

Python装饰器函数是一种高级技巧,用于修改其他函数的功能。它们可以通过将一个函数作为输入,并返回一个新函数来扩展或改变函数的行为。装饰器函数可以用于许多不同的应用,以下是一些常见的应用场景。

1. 日志记录:装饰器函数可以用于记录函数的调用信息,帮助排查错误或分析性能问题。通过在函数调用前后打印日志信息,可以了解函数的输入参数和输出结果,以及函数的执行时间。

import time

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

@log_decorator
def my_function():
    print("Running my_function")

my_function()

输出:

Calling function my_function
Running my_function
Function my_function took 0.001 seconds

2. 权限验证:装饰器函数可以用于验证用户的权限或身份。通过在需要验证的函数之前加上装饰器,可以确保只有具有足够权限的用户可以访问该函数。

def authenticated_decorator(func):
    def wrapper(*args, **kwargs):
        if is_authenticated():
            return func(*args, **kwargs)
        else:
            raise Exception("Unauthorized access")
    return wrapper

@authenticated_decorator
def protected_function():
    print("Running protected_function")

protected_function()  # 只有当用户通过身份验证时才会执行

3. 缓存结果:装饰器函数可以用于缓存函数的结果,避免重复计算。通过在函数内部使用一个字典来保存已经计算过的结果,并在下次调用时返回缓存的结果,可以提高函数的执行效率。

def cache_decorator(func):
    cache = {}

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

@cache_decorator
def expensive_function(n):
    print(f"Calculating result for {n}")
    return n * n

print(expensive_function(5))  # 计算并缓存结果
print(expensive_function(5))  # 直接返回缓存的结果

输出:

Calculating result for 5
25
25

4. 计时器:装饰器函数可以用于计算函数的执行时间,并返回该时间。通过在函数调用前后记录时间,并返回差值,可以测量函数的执行时间,帮助性能优化。

import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        return end_time - start_time, result
    return wrapper

@timer_decorator
def slow_function():
    time.sleep(2)
    return "Result"

execution_time, result = slow_function()
print(f"Function took {execution_time} seconds, result: {result}")

输出:

Function took 2.001441717147827 seconds, result: Result

装饰器函数的应用范围非常广泛,可以根据具体的需求创造出各种有用的装饰器。它们可以提供一种简洁而灵活的方式来修改函数的功能,使代码更加模块化,可读性更强,并提高代码的复用性。