温馨提示×

装饰器

装饰器(Decorator)是 Python 中一个非常强大的功能,它可以在不改变原函数代码的情况下,通过添加额外的功能来扩展原函数的功能。装饰器实际上是一个函数,它接受一个函数作为参数,并返回一个新的函数。

下面是一个简单的装饰器示例:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

def say_hello():
    print("Hello!")

say_hello = my_decorator(say_hello)

say_hello()

运行这段代码,输出如下:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

在上面的示例中,my_decorator 是一个装饰器函数,它接受一个函数 func 作为参数,并返回一个新的函数 wrapper。在 wrapper 函数内部,我们可以在原函数调用前后添加额外的功能。

在 Python 中,我们通常使用 @decorator 语法来应用装饰器,上面的示例可以用装饰器语法改写如下:

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

运行结果与之前相同。

装饰器可以接受参数,这样我们可以在装饰器内部配置装饰器的行为。例如,我们可以修改上面的装饰器,使其接受一个消息作为参数:

def my_decorator_with_args(message):
    def decorator(func):
        def wrapper():
            print("Something is happening before the function is called.")
            print(message)
            func()
            print("Something is happening after the function is called.")
        return wrapper
    return decorator

@my_decorator_with_args("Hello from decorator!")
def say_hello():
    print("Hello!")

say_hello()

运行结果如下:

Something is happening before the function is called.
Hello from decorator!
Hello!
Something is happening after the function is called.

除了以上的示例,装饰器还可以用来缓存函数、检查权限、日志记录等等。通过使用装饰器,我们可以使我们的代码更加简洁、可读性更高,并且更易于维护。

希望这篇教程可以帮助您更好地理解 Python 中的装饰器。如果您有任何问题或需要进一步的帮助,请随时向我询问。