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

Python中的装饰器函数及其实际应用场景

发布时间:2023-06-15 18:23:13

Python中的装饰器是一种特殊的函数,它可以动态地修改或改进函数的行为。限制让函数可以更灵活地复用和扩展。在Python中,装饰器是一种常见的编程技术,被广泛运用于各种场景中,比如Web应用、数据库、缓存、日志、异常处理等。

装饰器函数的定义形式如下:

def decorator_func(function_name):
    def wrapper(*args, **kwargs):
        # Do something before the function is called
        result = function_name(*args, **kwargs)
        # Do something after the function is called
        return result
    return wrapper

装饰器函数接受一个函数作为参数,并返回一个新的函数,新函数的行为被修改了。新函数成为原始函数的“包装器”。

常见的装饰器

1. 计时器装饰器

计时器装饰器可以测量函数调用的时间。这个装饰器适用于任何需要知道函数执行时间的情况。

import time
def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.monotonic()
        result = func(*args, **kwargs)
        end_time = time.monotonic()
        print(f"The function {func.__name__} took {end_time - start_time} seconds to execute.")
        return result
    return wrapper

@timer_decorator
def my_function():
    time.sleep(5)
    print("Function executed.")

my_function()

2. 日志器装饰器

日志器装饰器可以记录函数调用、异常和返回值,用于调试和日志记录。

import logging
logging.basicConfig(filename='log.txt', level=logging.DEBUG)

def logger_decorator(func):
    def wrapper(*args, **kwargs):
        logging.debug(f"Function {func.__name__} was called with args: {args} and kwargs: {kwargs}")
        try:
            result = func(*args, **kwargs)
            logging.debug(f"Function {func.__name__} returned: {result}")
            return result
        except Exception as e:
            logging.debug(f"Function {func.__name__} raised an exception: {e}")
            raise
    return wrapper

@logger_decorator
def my_function():
    print("Function executed.")
    return 1/0

my_function()

3. 缓存器装饰器

缓存器装饰器可以缓存函数的结果,加快函数的执行速度。当函数的输入相同时,可以直接返回缓存的结果,避免重复计算。

def cache_decorator(func):
    cache = {}

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

@cache_decorator
def my_function(a, b):
    print("Function executed.")
    return a + b

print(my_function(1, 2))  # prints "Function executed." and 3
print(my_function(1, 2))  # prints only 3

4. 数据验证装饰器

数据验证装饰器可以对函数输入进行验证,确保函数被正确调用。这个装饰器可以用于Web应用,防止攻击者通过注入恶意数据导致安全问题。

def validate_decorator(*types):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for i, (arg, typ) in enumerate(zip(args, types)):
                if not isinstance(arg, typ):
                    raise TypeError(f"Argument {i} must be of type {typ.__name__}.")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@validate_decorator(str, int)
def my_function(name, age):
    print(f"Hello, my name is {name} and I am {age} years old.")

my_function("John", 30)  # prints "Hello, my name is John and I am 30 years old."
my_function("John")      # raises TypeError "Argument 1 must be of type int."

装饰器函数是Python中的一个强大的工具,它可以用于改进多种不同的场景,并提高代码的复用性和可扩展性。掌握装饰器的技能对Python开发者来说是非常有用的。