Adorners because a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable.
def Now (): ... Print ' 2013-12-25 ' ... >>> f = now >>> f ()2013-12-25
A function object has a __name__
property that can get the name of the function:
>>> now. __name__ ' Now '>>> F.__name__'now'
Now, suppose we want to enhance now()
the function of functions, for example, to automatically print the log before and after a function call, but do not want to modify the definition of the now()
function, this way of dynamically adding functionality during the run of the code, called "Adorner" (Decorator).
Essentially, decorator is a higher-order function that returns a function. So, we want to define a decorator that can print the log, which can be defined as follows:
def log (func): def Wrapper (*args, * *kw) :print'call%s ():' % func. __name__ return func (*args, * *kw )return Wrapper
Observe the above log
, because it is a decorator, so accept a function as an argument and return a function. We will use the Python @ syntax to place the decorator at the definition of the function:
@log def Now (): Print ' 2013-12-25 '
Calling now()
a function will not only run the now()
function itself, but will also now()
print a line of logs before running the function:
>>> now () Call Now ():2013-12-25
Put @log
to now()
the definition of the function, the equivalent of executing a statement:
now = log (now)
Since log()
it is a decorator that returns a function, the original now()
function still exists, but the now variable with the same name points to the new function, and the call now()
executes the new function, which is the log()
function returned in the function wrapper()
.
wrapper()
The function's parameter definition is (*args, **kw)
, therefore, the wrapper()
function can accept calls of arbitrary arguments. wrapper()
inside the function, the log is printed first and then the original function is called.
If the decorator itself needs to pass in parameters, it is necessary to write a higher-order function that returns decorator, which is more complex to write. For example, to customize the text of a log:
16. Decorative Device