Python编程中的装饰器深度解析

装饰器本质上是一个接受函数作为参数并返回新函数的高阶函数。下面是一个简单装饰器的例子:

def simple_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

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

say_hello()

当执行 say_hello() 时,输出将是:

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

这里,@simple_decorator 语法等同于 say_hello = simple_decorator(say_hello)。装饰器 simple_decorator 接收一个函数 say_hello 作为参数,并返回一个新的函数 wrapper,这个新函数在调用原始函数前后执行一些额外的操作。

接下来,我们来看一个稍微复杂一点的例子,即带参数的装饰器。这需要我们使用到 *args 和 **kwargs,以便我们的装饰器可以处理任何被装饰的函数的参数:

def decorator_with_args(prefix):
    def actual_decorator(func):
        def wrapper(*args, **kwargs):
            print(f"{prefix} is happening before the function is called.")
            result = func(*args, **kwargs)
            print(f"{prefix} is happening after the function is called.")
            return result
        return wrapper
    return actual_decorator

@decorator_with_args("Decorated")
def add(x, y):
    return x + y

print(add(2, 3))

在这个例子中,装饰器 decorator_with_args 现在接受一个参数 prefix,并返回实际的装饰器 actual_decoratoractual_decorator 再返回包装函数 wrapper,该函数可以正确处理传递给被装饰函数的任意数量的位置参数和关键字参数。

最后,我们探讨一下装饰器的嵌套使用,这可以让装饰器的应用变得更加灵活和强大。嵌套装饰器意味着我们可以将多个装饰器应用到同一个函数上,每个装饰器负责不同的功能:

def outer_decorator(func):
    def wrapper():
        print("Outer wrapper doing work.")
        func()
    return wrapper

def inner_decorator(func):
    def wrapper():
        print("Inner wrapper doing work.")
        func()
    return wrapper

@outer_decorator
@inner_decorator
def do_work():
    print("The real work is done here.")

do_work()

当我们运行 do_work() 时,可以看到以下输出:

Outer wrapper doing work.
Inner wrapper doing work.
The real work is done here.

这表明两个装饰器都按预期工作,且它们的应用顺序是从内到外。

posted @ 2025-06-23 15:41  修BUG狂人  阅读(18)  评论(0)    收藏  举报