前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

一文掌握Python 函数装饰器

qiguaw 2025-03-12 19:56:28 资源文章 42 ℃ 0 评论

Python 装饰器是一项强大的功能,允许您在不更改其代码的情况下修改或扩展函数的行为。它们通常用于日志记录、实施访问控制、测量执行时间等。

1. 什么是函数装饰器?

在 Python 中,函数是一等对象。这意味着他们可以:

  • 存储在变量中
  • 作为参数传递给其他函数
  • 从函数返回

使用这个概念,装饰器是包装另一个函数以修改或增强其行为的函数。

装饰器是如何工作的?

装饰器只是一个函数,它将另一个函数作为输入,将其包装在另一个函数中,并返回修改后的函数

2. 创建基本函数装饰器

让我们从一个简单的装饰器开始,它在调用函数后打印 Start... before 和 End...

def decorator_function(original_function):
    def wrapper():
        print("Start......")
        original_function()
        print("End......")
    return wrapper

def say_hello():
    print("Hello, World!")

decorated_function = decorator_function(say_hello)
decorated_function()
Start......
Hello, World!
End......

以下是发生的情况:

  • decorator_functionsay_hello 作为参数。
  • 它定义了一个内部函数包装器,该包装器在调用 say_hello() 之前和之后添加额外的行为。
  • 最后,它返回包装器,将 say_hello() 替换为修改后的版本。

3. 使用@装饰器语法

Python 提供了一个快捷方式,而不是手动调用 decorator_function(say_hello):

@decorator_function
def say_hello():
    print("Hello, World!")

say_hello()

@decorator_function会自动应用装饰器,使代码更具可读性。

4. 使用 <*args>和 <**kwargs>处理函数参数

如果我们想装饰一个接受参数的函数怎么办?我们使用 *args**kwargs 修改包装函数以接受任意数量的参数:

def decorator_function(original_function):
    def wrapper(*args, **kwargs):
        print("Start......")
        result = original_function(*args, **kwargs)
        print("End......")
        return result
    return wrapper

@decorator_function
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
Start......
End......
Hello, Alice!

现在,我们的装饰器可以与任何函数一起使用,无论其参数如何

5. 创建一个 Timer Decorator 来测量执行时间

装饰器的一个实际用途是测量执行时间。以下是创建计时器装饰器的方法:

import time

def timer_decorator(original_function):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = original_function(*args, **kwargs)
        end_time = time.time()
        print(f"Execution time: {end_time - start_time:.5f} seconds")
        return result
    return wrapper

@timer_decorator
def example_function():
    time.sleep(1)  # Simulating a delay

example_function()
Execution time: 1.00025 seconds

此装饰器有助于跟踪 Python 程序中的性能。

6. 将多个装饰器应用于一个函数

你可以通过堆叠多个装饰器来将它们应用于单个函数:

@timer_decorator
@decorator_function
def say_hello():
    time.sleep(1)
    print("Hello !!!")

say_hello()
Start......
Hello !!!!!
End......
Time: 1.0022363662719727

Python 从下到上执行装饰器,因此首先运行 decorator_function,然后timer_decorator

7. 装饰器的真实用例

  • 日志记录:自动记录函数调用。
  • 身份验证:限制某些用户的访问。
  • 缓存:存储结果以优化性能。
  • 基准测试:测量函数的执行时间。

结论

装饰器是 Python 中的一个强大工具,可帮助修改函数行为,而无需修改其代码。在这篇文章中,我们介绍了:
装饰器的工作原理
如何使用
@ 语法应用装饰器
如何动态处理函数参数
如何使用定时器装饰器测量执行时间
真实用例

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表