Decorators are used to wrap functions, add extra functionality, and should be able to decorate a batch of functions to reduce code reuse.
a simple decorator
A function receives a function object as a parameter and returns a function object, such that a function can become a decorator, as defined below:
def deco (func): Def _deco (*args): print "Do Something" func (*args) return _deco
In the above decorator, Func is called the modified function, and some additional initialization is done before the Func is executed.
After the decorator definition is complete, use @ To modify the function, as shown here:
@deco #实际相当于执行了f = Deco (f) def f (x): Print X
After the above processing, view F's function name has become "_deco"
Print Fprint deco (f)
The operating result is:
<function _deco at 0x00000000022314a8>
<function _deco at 0x0000000002231518>
After the description finishes, F is the shallow copy version of Deco (f).
Then, when we call F ("Hello"), we get the following output:
Do something
Hello
Modifiers with parameters
Decorator is a function form, of course, you can pass in parameters, at this point, you must add a layer of nested to receive parameters, as follows:
Def deco_args (a, b): # a,b is the parameter def deco (func) required by the decorator: def _deco (*args): # * Args is the parameter required for the function being wrapped print "do Something " func (*args) #do something return _deco return deco # closures are required for @deco_args ( ) # equivalent to F = deco_args (f) def f (x): print x
This article is from the "Nameless" blog, please be sure to keep this source http://xdzw608.blog.51cto.com/4812210/1603620
Python advanced programming-part3 Decorator Prelude