繁体   English   中英

python中的函数装饰器会隐式调用装饰后的函数吗?

[英]Do function decorators in python call the decorated function implicitly?

我的头衔可能会引起误解。 我的问题来自此代码段。

class myDecorator(object):

    def __init__(self, f):
        print "inside myDecorator.__init__()"
        f() # Prove that function definition has completed

    def __call__(self):
        print "inside myDecorator.__call__()"

@myDecorator
def aFunction():
    print "inside aFunction()"

print "Finished decorating aFunction()"

#aFunction()

当我执行上面的代码时,我得到的输出为

inside myDecorator.__init__()
inside aFunction()
Finished decorating aFunction()

但是,我认为输出应仅为

Finished decorating aFunction()

只是装饰函数,调用构造函数并执行myDecorator对象。我的印象是,只有当aFunction()时,装饰器模式才会执行。 为什么会这样呢?

关于装饰器的另一个问题:

链接将修饰符解释为@ is just a little syntax sugar meaning "pass a function object through another function and assign the result to the original function.

所指的功能对象,另一个功能和原始功能是什么?

“功能对象”是aFunction “另一个功能”是myDecorator “原始功能”实际上应读为“原始功能名称 ”,在这种情况下为“ aFunction”。

def aFunction(...)
   ...

aFunction = myDecorator(aFunction)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM