要理解装饰器在 Python 中的工作原理,将它们视为一个两步过程会很有帮助:
定义了装饰器函数,它接受另一个函数作为参数。装饰器函数返回一个新函数,该函数为原始函数添加了附加功能。这是一个简单的例子来演示它是如何工作的:
def my_decorator(func): def wrapper(): print("Before the function is called.") func() print("After the function is called.") return wrapper@my_decoratordef say_hello(): print("Hello, world!")在上面的示例中,my_decorator 是一个接受另一个函数作为参数 (func) 的函数。然后它定义一个新函数(包装器),在调用 func 之前和之后打印一条消息。@my_decorator 语法是将装饰器应用到 say_hello 函数的一种简写方式。这相当于调用 say_hello = my_decorator(say_hello)。当调用 say_hello 时,装饰器会自动应用,输出将如下所示:Before the function is called.Hello, world!After the function is called.需要使用Python装饰器的实时场景。1. 测量执行时间假设创建了一个方法,要检查它花费了多少时间。import timedef measure_time(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() execution_time = end_time - start_time print(f"Execution time: {execution_time} seconds") return result return wrapper@measure_timedef my_function(): time.sleep(2)my_function()2. 日志记录假设您想使用下面的代码片段来记录您的函数,您可以轻松地做到这一点。def log_function(func): def wrapper(*args, **kwargs): print(f"Calling function: {func.__name__}") print(f"Arguments: {args}") print(f"Keyword Arguments: {kwargs}") result = func(*args, **kwargs) return result return wrapper@log_functiondef my_function(x, y): return x + yprint(my_function(2, 3))3. 输入验证下面的脚本用于验证调用函数时传递的参数。def validate_input(func): def wrapper(*args, **kwargs): for arg in args: if not isinstance(arg, int): raise TypeError("Input arguments must be integers") for value in kwargs.values(): if not isinstance(value, int): raise TypeError("Keyword arguments must be integers") return func(*args, **kwargs) return wrapper@validate_inputdef add_numbers(a, b): return a + bprint(add_numbers(2, 3))