带参数的 Python 装饰器

17 Mar 2025 | 4 分钟阅读

在本教程中,我们将讨论 Python 中的带参数装饰器,但在开始此主题之前,用户必须学习 Python 中的装饰器 和函数装饰器。

装饰器是 Python 中一个非常强大且有用的工具,因为它可以让用户修改函数或类的行为。

Python 函数可以被视为头等公民,就像对象一样。

  • 函数可以被引用给一个变量。
  • 函数可以作为参数传递给其他函数。
  • 函数可以从函数中返回。

带参数的装饰器就像普通的装饰器一样。

语法

带参数装饰器的代码实现

当我们执行此代码时,执行将从左到右开始,它将调用 decorator(params) 来返回函数对象 func_obj。然后 func_obj(function_name) 将通过使用 func_obj 被调用。在内部函数中,将执行所需的操作,并将实际函数的引用返回以分配给 function_name。现在,用户可以使用 function_name() 来调用已应用装饰器的函数。

如何实现带参数的装饰器

首先,我们将看到如果我们直接运行参数代码而不实现任何值,我们可以得到什么输出。

在这里,在上面的代码中,由于 params 为空,我们可能会遇到一些错误。

让我们一步一步来理解

输出

Inside the Decorator: 
Inside the Inner Function: 
'Decorated the function'
Inside the actual function

代码执行的可视化表示

装饰器执行内部

Decorators with Parameters in Python

内部函数执行内部

Decorators with Parameters in Python

装饰器函数执行

Decorators with Parameters in Python

最终输出执行

Decorators with Parameters in Python

在上面的代码中,我们将获得通过带参数装饰器调用的函数的输出。

替代方法

在下面的代码中,我们将看到如何以替代方式编写使用装饰器的函数代码。

输出

Inside the decorator
Inside the inner function
Decorated the function
Inside the actual function

现在我们将看到使用参数装饰器的不同示例,以便更好地理解该概念。

示例 1

输出

Inside the Decorator
Inside the inner function
I am studying COMPUTER SCIENCE AND ENGINEERING 
Inside the actual function

代码执行的可视化表示

Decorators with Parameters in Python

最终输出执行

Decorators with Parameters in Python

示例 2

输出

I am studying COMPUTER SCIENCE AND ENGINEERING 
Summation of values - 36
Computer
Science
and
Engineering

上面的示例也表明,内部函数可以访问外部函数的参数。

代码执行的可视化表示

Decorators with Parameters in Python

示例 3

输出

Decorator for 'string_Join'
Decorator for 'summation_1'

stringJoin process started ...
I am studying Computer Science and Engineering

summation process started ...
The sum is equal to: 1242

过程的可视化表示

返回 decorator_1

Decorators with Parameters in Python

返回 wrapper_1

Decorators with Parameters in Python
Decorators with Parameters in Python

执行 message_1

Decorators with Parameters in Python

执行 String_Join

Decorators with Parameters in Python

执行 summation_1

Decorators with Parameters in Python

最终输出执行

Decorators with Parameters in Python

结论

在本教程中,我们讨论了如何使用带参数的装饰器执行函数。我们还通过对参数的内部函数和外部函数的视觉表示来解释了示例。