Home >Backend Development >Python Tutorial >Detailed explanation of python decorators
The syntax of the decorator starts with @, followed by the name of the decorator function and optional parameters.
Following the decorator declaration are the decorated function and the optional parameters of the decorated function, as follows:
@decorator(dec_opt_args)
def func(func_args):
....
In fact, overall Speaking of which, a decorator is actually a function, a function used to wrap a function. The decorator is called when the function declaration is completed, and the function declared after the call is replaced by a function decorated by the decorator.
For example:
def deco(func): ... return func @deco def foo(): print 'foo' #----------------------------------- #等价如下: def deco(func): ... return func def foo(): print 'foo' foo = deco(foo) 如下例子: def deco1(func): print 'ok' return func @deco1 def foo(): print 'foo' foo() #输出-------------- #ok #foo #------------------
If you don’t use decorators, you can do the following:
def deco1(func): print 'ok' return func def foo(): print 'foo' print foo #<function foo at 0x00AFE6F0> foo = deco1(foo) foo() #输出-------------- #ok #foo #------------------
Comparing the two, you can see that using decorators is so simple and flexible. Especially in enterprise-level development.
You can also use multiple decorators overlappingly:
def deco1(func): print 'deco1' return func def deco2(func): print 'deco2' return func @deco1 @deco2 def foo(): print 'foo' foo() #输出如下:----------- #deco2 #deco1 #foo #---------------------
Equivalent to:
@deco1 @deco2 def foo(arg):pass -----------与下等效---------- foo = deco1(deco2(foo()))
2. Decorators with and without parameters
The above examples basically have parameters, and no parameters are simpler .
1. No ginseng
@deco1
@deco2
def foo(arg):pass
------------------------
foo = deco1(deco2(foo()))
2, there are ginseng
@deco1(deco_arg)
@deco2
def foo(arg):pass
---------- ----------
foo = deco1(deco_arg)(deco2(foo()))
Returns a decorator that takes a function as a parameter
3. Uses
1. Reference log
2 , Add timing logic to test performance
3. The ability to add transactions to functions
4. Example
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() #输出如下:-------- #[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 #------------------