Transfer from http://www.cnblogs.com/BeginMan/p/3173328.html
A decorator (Decorators)
Decorator syntax beginning with @, followed by the name of decorator functions, optional parameters.
Decorative declaration is followed by an optional parameter of the function and decorative function to be decorated, as follows:
@decorator(dec_opt_args) def func(func_args): ....
In fact, overall speaking, in fact, is a decorator function, a wrapper function for function and decorative function is called when the statement is completed, after calling a function declared after the function is replaced by a decorative decorator.
Such as:
def deco(func): ... return func @deco def foo(): print 'foo' #----------------------------------- # Equivalent is as follows: def deco(func): ... return func def foo(): print 'foo' foo = deco(foo)
Examples are as follows:
def deco1(func): print 'ok' return func @deco1 def foo(): print 'foo' foo() # Output -------------- #ok #foo #------------------
If you do not use the decorator can be as follows:
def deco1(func): print 'ok' return func def foo(): print 'foo' print foo #<function foo at 0x00AFE6F0> foo = deco1(foo) foo() # Output -------------- #ok #foo #------------------
Under contrast between the two can be found using the decorator is so easy and flexible. Especially in the development of enterprise-class.
You can also use a plurality of decorative overlay:
def deco1(func): print 'deco1' return func def deco2(func): print 'deco2' return func @deco1 @deco2 def foo(): print 'foo' foo() # Output is as follows: ----------- #deco2 #deco1 #foo #---------------------
Equivalent to:
@deco1 @deco2 def foo(arg):pass ---------- ----------- lower equivalent foo = deco1(deco2(foo()))
Second, there is participation, no arguments decorator
The above examples are all substantially parameters and parameter easier.
1, no-argument
@deco1 @deco2 def foo(arg):pass --------------------- foo = deco1(deco2(foo()))
2, reference
@deco1(deco_arg) @deco2 def foo(arg):pass --------------------- foo = deco1(deco_arg)(deco2(foo()))
Back decorator to function as a parameter
Third, use
1, reflog
2, the timing logic to increase detection performance
3, adding the ability to function Affairs
Fourth, examples
from time import ctime,sleep def deco(func): def decoIn(): print '[%s]:%s called' %(ctime(),func.__name__) return func return decoIn @deco def foo(): pass foo() sleep(4) for i in range(2): sleep(1) foo() # Output is as follows: -------- #[Fri Jul 05 10:45:04 2013]:foo called #[Fri Jul 05 10:45:09 2013]:foo called #[Fri Jul 05 10:45:10 2013]:foo called #------------------
Five highly recommended reading: