Python 装饰器的常见使用案例:实际示例

2023-03-30 00:00:00 示例 案例 常见

Python 装饰器是一种将一个函数作为输入,返回另一个函数作为输出的函数,通常用于修改或增强原始函数的行为。以下是一些常见的使用案例:

记录函数运行时间

import time

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

@timing_decorator
def some_function():
    time.sleep(1)

some_function() # Function some_function took 1.0002381801605225 seconds to run

权限检查

def check_permission_decorator(func):
    def wrapper(user, *args, **kwargs):
        if user.is_admin:
            return func(user, *args, **kwargs)
        else:
            raise Exception("Permission denied")
    return wrapper

class User:
    def __init__(self, name, is_admin=False):
        self.name = name
        self.is_admin = is_admin

@check_permission_decorator
def some_admin_function(user):
    print(f"{user.name} is an admin")

admin_user = User("Alice", is_admin=True)
some_admin_function(admin_user) # Alice is an admin

normal_user = User("Bob")
some_admin_function(normal_user) # Exception: Permission denied

缓存函数结果

def cache_decorator(func):
    cache = {}

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

    return wrapper

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

print(some_expensive_function(2)) # Calculating result for 2 \n 4
print(some_expensive_function(2)) # 4 (cached)

这些示例只是 Python 装饰器的一些用例,实际上,它们可以应用于许多其他场景。

相关文章