📜  Python中的装饰器(1)

📅  最后修改于: 2023-12-03 15:19:31.350000             🧑  作者: Mango

Python中的装饰器

在Python中,装饰器是一种函数,它可以修改其他函数的功能。装饰器本身可以是一个简单的函数,但是有时候需要使用闭包来保持内部函数的状态。

装饰器的语法

装饰器的语法是使用“@”符号来表示。装饰器可以被定义成一个普通函数,然后使用“@”符号进行装饰。

@decorator
def function():
    # some code
基本的装饰器

以下是一个基本的装饰器的例子。它可以输出函数的执行时间。

import time

def my_decorator(func):
    def wrapper():
        print('Before the function is called.')
        start_time = time.time()
        func()
        end_time = time.time()
        print('After the function is called.')
        print('Elapsed time: ', end_time - start_time)

    return wrapper

@my_decorator
def say_hello():
    print('Hello World!')

say_hello()

输出为:

Before the function is called.
Hello World!
After the function is called.
Elapsed time:  0.0
带参数的装饰器

装饰器可以带有参数。为了实现带参数的装饰器,需要定义一个返回装饰器的函数。

以下是一个带有参数的装饰器的例子,可以指定要打印的消息:

def make_message(message):
    def decorator(func):
        def wrapper():
            print(message)
            func()

        return wrapper

    return decorator

@make_message('This is a message.')
def say_hello():
    print('Hello World!')

say_hello()

输出为:

This is a message.
Hello World!
类装饰器

装饰器也可以是类。类装饰器和函数装饰器的语法和行为是一样的,但是通过使用类装饰器可以保持装饰器状态:

class DecoratorClass:
    def __init__(self, func):
        self.func = func

    def __call__(self):
        print('Before the function is called.')
        self.func()
        print('After the function is called.')

@DecoratorClass
def say_hello():
    print('Hello World!')

say_hello()

输出为:

Before the function is called.
Hello World!
After the function is called.
多个装饰器

一个函数可以被多个装饰器装饰。它们的执行顺序与装饰器在函数上声明的顺序相反。

def my_decorator1(func):
    def wrapper():
        print('Before my_decorator1 is called.')
        func()
        print('After my_decorator1 is called.')

    return wrapper

def my_decorator2(func):
    def wrapper():
        print('Before my_decorator2 is called.')
        func()
        print('After my_decorator2 is called.')

    return wrapper

@my_decorator1
@my_decorator2
def say_hello():
    print('Hello World!')

say_hello()

输出为:

Before my_decorator2 is called.
Before my_decorator1 is called.
Hello World!
After my_decorator1 is called.
After my_decorator2 is called.
小结

在Python中,装饰器是一种函数,它可以修改其他函数的功能。装饰器的语法是使用“@”符号来表示。装饰器可以带有参数,也可以是类。一个函数可以被多个装饰器装饰。