Output your code
inside myDecorator.__init__() inside aFunction() Finished decorating aFunction() inside myDecorator.__call__()
First, do you know what this @decorator syntax means?
@decorator def function(a): pass
is another way of saying:
def function(a): pass function = decorator(function)
So in your case
@myDecorator def aFunction(): print ("inside aFunction()")
means just
def aFunction(): print ("inside aFunction()") aFunction = myDecorator(aFunction)
First, you basically create a new instance of the myDecorator class by calling its constructor (__init__) and passing it an object to a function function. Then it performs printing and the specified function. Also note that this happens when the function is loaded by the interpreter, and not when it is executed, so if you import something from this file, it will then execute, rather than use or call.
Then, by executing aFunction() , when aFunction is still referencing an instance of myDecorator, it calls the __call__ myDecorator method, which is executed. Note that f() in this case means the same as f.__call__(f) , since the __call__ method __call__ used to enable and override the default behavior of calling objects (in simplification, any object can be called if it has a method __call__ ).
If you want to execute the aFunction function when you call it, you must assign it to the instance variable in __init__ and call it in __call__ myDecorator.
Wikiii122
source share