Python中的 call() 装饰器
Python装饰器是该语言的重要功能,允许程序员修改类的行为。这些功能在功能上添加到现有代码中。这是在编译时修改程序时的一种元编程。装饰器可用于在函数或类中注入修改后的代码。装饰器允许修改程序以添加任何具有特殊作用的代码。装饰器在你装饰的函数的定义之前被调用。
装饰器的使用可以用下面的例子来解释。假设我们编写一个程序来使用另一个函数。代码如下:
# Code to explain Decorators
def decorating(function):
def item():
print("The function was decorated.")
function()
return item
def my_function():
print("This is my function.")
my_function()
decorate = decorating(my_function)
decorate()
输出
This is my function.
The function was decorated.
This is my function.
首先,由于函数调用 my_function() 出现“这是我的函数”。第二组输出是因为 Decorating函数。
同样的事情也可以通过使用装饰器来完成。下面的代码解释了这一点。请注意,装饰语句是在要装饰的函数之上定义的。
# Code to implement the usage
# of decorators
def decorating(function):
def item():
print("The function was decorated.")
function()
return item
# using the "@" sign to signify
# that a decorator is used.
@decorating
def my_function():
print("This is my function.")
# Driver's Code
my_function()
输出
The function was decorated.
This is my function.
call() 装饰器
call() 装饰器用于代替辅助函数。在Python或任何其他语言中,我们使用辅助函数来实现三个主要目的:
- 确定方法的目的。
- 辅助函数在其工作完成后立即被删除。和
- 辅助函数的目的与装饰函数的目的相匹配。
下面的例子将说明调用装饰器方法的意义。在此示例中,我们将使用辅助函数构建前“n”个数字的双精度数列表。
代码如下:
# Helper function to build a
# list of numbers
def list_of_numbers(n):
element = []
for i in range(n):
element.append(i * 2)
return element
list_of_numbers = list_of_numbers(6)
# Output command
print(len(list_of_numbers),
list_of_numbers[2])
输出
6, 4
上面的代码也可以使用 call() 装饰器编写:
# Defining the decorator function
def call(*argv, **kwargs):
def call_fn(function):
return function(*argv, **kwargs)
return call_fn
# Using the decorator function
@call(6)
def list_of_numbers(n):
element = []
for i in range(n):
element.append(i * 2)
return element
# Output command
print(len(list_of_numbers),
list_of_numbers[2])
输出
6, 4
正如所观察到的,输出与以前相同,这意味着 call() 装饰器的工作方式几乎与辅助函数完全相同。