Since the function is also an object, and the function can be assigned to other variables (value = Pringname ()) as a special object, the function can also be called through a variable, and here is a simple example:
1>>>defprintname ():2...Print("My name is Jobs")3 ... 4>>> name =Printname5>>>6>>>Printname ()7My Name isJobs8>>>name ()9My Name isJobs
It is not difficult to see from the above code that the Printname () function is assigned to the name variable, and the Printname () function can also be called with the name variable. At this point they are the same, and here's a little bit of knowledge: the Function object has
A __name__ property that can get the name of the function:
Example:
1 2 >>> name. __name__ 3 ' Printname ' 4 >>> printname. __name__ 5 ' Printname ' 6 7
Now, suppose we want to enhance the function of the Printname function, for example, to automatically print the log before and after a function call, but do not want to modify the definition of the Printname 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:
Example one:
1 2 def log (func): 3 def wrapper (*args,**kw):4print'call%s ()' % Func. __name__ 5 return func (*args,**kw)6return wrapper7 ...
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:
1 >>> @log2def printname ():3print(" My name is Jobs")45 >>> printname ( )6callprintname ()7 is Jobs
Example two:
1>>>2>>>@log3...defprintage ():4...Print '%s,my Age is'%Printname ()5 ... 6>>> job =printage ()7 Call printage ()8 Call printname ()9My Name isJobsTenNone,my Age is120
when you call Printname or Printage (), not only will the function itself be called, but some logs will be printed before the function is called. Placing @log before the Printage () function is equivalent to executing a statement:
name= log(printName)
Since log() it is a decorator, return a function, so the original now() function still exists, just now the name of Printname () a new function, so call Printname () will execute the new function, that is, return in the log() function wrapper()function.
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:
1 deflog (text):2 defDecorator (func):3 defWrapper (*args, * *kw):4 Print '%s%s ():'% (text, func.)__name__)5 returnFunc (*args, * *kw)6 returnwrapper7 returnDecorator
This 3-layer nesting
1>>>deflog (text):2...defDecorator (func):3...defWrapper (*args,**kw):4...Print '%s%s ():'% (Text,func.__name__)5...returnFunc (*args,**kw)6...returnwrapper7...returnDecorator8 ... 9>>> @log ('Excute')Ten...defprintname (): One...Print("My name is jobs!") A ... ->>>Printname () - Excute printname (): theMy Name isjobs! ->>>
Let's parse the above statement, execute it first, log(‘execute‘) return the decorator function, call back the function, the argument is the now function, the return value is the wrapper function.
There is no problem with the definitions of the two decorator, but the last step is not the case. Because we're talking about functions and objects, and it has __name__ properties like that, but you see the functions after the decorator decoration, and they __name__ have changed from the original ‘printName ‘wrapper‘ :
>>> Printname. __name__ ' wrapper '
Because the name of the function returned is the same, wrapper() ‘wrapper‘ so you need to copy the properties of the original function __name__ into the wrapper() function, otherwise, some code that relies on the function signature will be executed with an error.
There is no need to write wrapper.__name__ = func.__name__ such code, Python functools.wraps is built to do this, so a complete decorator is written as follows:
1>>>deflog (func):2 ... @functools. Wraps (func)3...defWrapper (*args,**kw):4...Print 'Call %s ():'%func.__name__5...returnFunc (*args,**kw)6...returnwrapper7 ... 8>>>
The decorator can also be used for the parameters of the stay:
Import Functools def log (text): def Decorator (func): @functools. Wraps (func) def Wrapper (*args, * *kw) : Print ' %s%s (): ' % (text, func. __name__) return func (*args, * *kw )return Wrapper return decorator
This is an example of an update that we would like to help you understand:
1>>>defDeco (func):2...def_deco (A, b):3...Print("before MyFunc () called.")4... ret =func (A, b)5...Print("After called.result:%s"%ret)6...returnret7...return_deco8 ... 9 Ten>>>@deco One...defMyFunc (A, b): A...Print("MyFunc (%s,%s) called."%(A, b)) -...returnA +b - ... the>>> MyFunc () - before MyFunc () called. -MyFunc () called. -After Called.result:3 +3 ->>>
Additional notes:
In fact, the adorner is a function, a function that can be used to wrap functions, and finally return a modified function (here, such as adding a log, such as the above example.) ) to re-assign the original identifier and permanently lose access to the original function object.
Python's Decorator