首页
学习
活动
专区
圈层
工具
发布
31 篇文章

Python基础语法-函数-函数装饰器-多个装饰器

多个装饰器

Python允许我们使用多个装饰器来装饰一个函数。例如,下面是一个使用两个装饰器的示例:

代码语言:javascript
复制
def decorator_one(func):
    def wrapper():
        print('Decorator one before.')
        func()
        print('Decorator one after.')
    return wrapper

def decorator_two(func):
    def wrapper():
        print('Decorator two before.')
        func()
        print('Decorator two after.')
    return wrapper

@decorator_one
@decorator_two
def say_hello():
    print('Hello World!')

say_hello()

在这个例子中,我们定义了两个装饰器函数,分别为“decorator_one”和“decorator_two”。然后,我们将这两个装饰器应用于我们的“say_hello”函数,其中“decorator_one”是第一个应用的装饰器,因此它将包装器函数作为参数传递给“decorator_two”装饰器函数。

最后,我们调用“say_hello”函数,它将在执行前和执行后打印四条消息,分别是两个装饰器的前置和后置消息,以及我们原始函数的输出。

下一篇
举报
领券