【发布时间】: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