【问题标题】:Do function decorators in python call the decorated function implicitly?python中的函数装饰器是否隐式调用装饰函数?
【发布时间】:2013-09-12 03:52:04
【问题描述】:

我的标题可能具有误导性。我的问题来自这段代码 sn-p。

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()时才会执行装饰器模式。为什么会这样?

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

这个link将装饰器解释为@ is just a little syntax sugar meaning "pass a function object through another function and assign the result to the original function.

this所指的函数对象、另一个函数和原函数是什么?

【问题讨论】:

  • 它没有被隐式调用,但你在你的 init 中显式调用它:f()。在aFunction 可以传递给myDecorator 的实例之前,显然需要创建一个初始化的实例。

标签: python function decorator function-object


【解决方案1】:

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

def aFunction(...)
   ...

aFunction = myDecorator(aFunction)

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 2017-01-15
    • 1970-01-01
    • 2017-12-11
    • 2014-07-21
    • 2020-07-13
    • 2017-08-01
    • 2023-02-08
    • 2018-03-07
    相关资源
    最近更新 更多