了解装饰者的行为

2024-09-29 23:22:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想了解这个代码中的装饰器行为

abc.py

def my_decorator_module(some_function):
    def wrapper():
        num = 10
        if num == 10:
            print('yess')
        else:
            print('no')

        some_function()

        print('print after some_function() called')

    return wrapper()

并将此函数称为decorator

x.py

from abc import my_decorator_module

@my_decorator_module
def just_some_function():
    print("Wheee!")

输出为

yess
Wheee!
print after some_function() called

当我执行x.py文件return me输出时,我没有调用x.py文件中的just_some_function()事件,为什么?你知道吗


Tags: pyreturnmydeffunctiondecoratorsomewrapper
2条回答

您没有显式地调用just_some_function(),但是您的“decorator”调用了,参见最后一行:

def my_decorator_module(some_function):
    def wrapper():
        num = 10
        if num == 10:
            print('yess')
        else:
            print('no')

        some_function()

        print('print after some_function() called')

    # here !!!   
    return wrapper()

这实际上是一个错误的实现-您的装饰程序不应该返回调用wrapper的结果,而是返回wrapper函数本身:

    return wrapper

如果您不明白原因:@decorator语法只是语法糖,那么:

@decorator
def somefunc():
    print("somefunc")

实际上只是一个捷径:

def somefunc():
    print("somefunc")

somefunc = decorator(somefunc)

因此,您的decorator必须返回一个函数对象(或任何可调用的FWIW),通常-但不一定-一些包装器将负责调用修饰函数(最好返回结果)。你知道吗

因为您在从外部装饰函数返回它之前已经调用了wrapper。别那么做。你知道吗

return wrapper   # not wrapper()

tutorial you're following早先引入了返回函数的概念,而不是调用它们并返回它们的结果;这就是您需要在这里做的事情。你知道吗

相关问题 更多 >

    热门问题