我的标题可能具有误导性。我的问题来自这个代码片段。
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.
this所指的函数对象,另一个函数和原始函数是什么?