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

Python中的装饰器的实现和使用方法

发布时间:2023-06-26 12:05:25

Python中的装饰器是一种特殊的语法结构,它可以在函数或类的定义前增加一些额外的功能,让程序的灵活性更高。

装饰器的实现方式通常使用函数,使用def定义一个方法,方法的参数为被装饰函数。在定义被装饰函数时,需要在函数前添加@符号接上封装器函数,这样被装饰函数就会被封装器函数所控制,被封装器所定义的功能就能添加到被装饰函数里。

下面我们来看一下装饰器的使用方法。

装饰器的使用方法:

1.定义装饰器函数

首先需要定义装饰器函数,如下所示:

def decorator(func):
    def wrapper(*args,**kwargs):
        print("Before the function is called.")
        func(*args,**kwargs)
        print("After the function is called.")
    return wrapper

2.使用装饰器

使用装饰器需要在函数前面添加@符号,后面接上定义的装饰器函数名。例如:

@decorator
def greet(name):
   print(f"Hello, {name}")

3.运行结果

当使用@greet装饰函数时,运行结果将会变成这样:

>>> greet("John")
Before the function is called.
Hello, John
After the function is called.

在这个例子中,函数greet被函数decorator包装。包装器(wrapper)的目标是在函数被调用之前和之后执行附加功能(本例中为日志)。

因此,当调用greet()函数时,装饰器包装器首先记录句子"Before the function is called.",然后调用原始函数,并在日志上记录句子"Hello, John"。最后,记录句子"After the function is called."并返回调用的结果。

4.给装饰器传递参数

有时,您可能需要传递参数给装饰器。为此,可以将装饰器函数定义为接受参数并返回另一个包装器函数。

def repeat(num):
    def decorator_repeat(func):
        def wrapper(*args,**kwargs):
            for i in range(num):
                print(f"Executing {i+1} of {num}")
                func(*args,**kwargs)
        return wrapper
    return decorator_repeat

在这个例子中,函数repeat和decorator_repeat分别处理跟踪执行次数和包装函数的问题。函数wrapper不变。

假设您有一个函数say_whee,希望它执行3次。以这种方式使用这个装饰器:

@repeat(num=3)
def say_whee(name):
    print(f"Whee! {name}")

您将得到下面的输出结果:

>>> say_whee("Tom")
Executing 1 of 3.
Whee! Tom
Executing 2 of 3.
Whee! Tom
Executing 3 of 3.
Whee! Tom

总结

装饰器是一个强大的Python功能。它允许在不修改原始代码的情况下修改代码的行为。即可以灵活地控制类或函数的行为。同时,它还可以通过复合实现高级特性,例如函数重载,函数链和参数化装饰器等。