Decorator
The decorator design pattern allows you to dynamically wrap existing objects or functions so that you can modify existing responsibilities and behaviors to dynamically extend existing functions. In fact, this is the concept of AOP in other languages, which separates the real functions of objects or functions from other auxiliary functions.
Ii. decorator in Python
In python, decorator is usually used to input a function. After decoration, another function is returned. Common functions are generally implemented using decorator, such as staticmethod and classmethod provided by python.
The decorator has two forms:
@
Def Foo ():
Pass
Equivalent:
Def Foo ():
Pass
Foo = a (FOO)
The second type includes parameters:
@ A (ARG)
Def Foo ():
Pass
It is equivalent:
Def Foo ():
Pass
Foo = a (ARG) (FOO)
We can see that the first type of decorator is a function that returns the function, and the second type of decorator isReturn Function.
The decorator in python can be used at the same time, as shown below:
@
@ B
@ C
Def F (): Pass
# It is same as below
Def F (): Pass
F = A (B (C (F )))
Iii. Common decorator instances in Python
Decorator is usually usedPerform permission authentication, logging, modifying input parameters, preprocessing of returned results, and even truncation of function execution before execution.
Instance 1:
From Functools Import Wraps
Def Logged (func ):
@ Wraps (func)
Def With_logging (* ARGs, ** kwargs ):
Print (Func. _ Name __ () + " Was called " )
Return Func (* ARGs, ** kwargs)
Return With_logging
@ Logged
DefF (x ):
"""Does some math"""
ReturnX + x * x
Print(F._ Name __)#Prints 'F'
Print(F._ Doc __)#Prints 'Does some math'
Note functools. the role of the wraps () function: when calling a decorated function is equivalent to calling a new function, you can view function parameters, comments, and even function names, you can only view information about the decorator and the information about the function to be packaged is lost. Wraps can help you transfer this information, see http://stackoverflow.com/questions/308999/what-does-functools-wraps-do
Refer:
Http://www.cnblogs.com/Lifehacker/archive/2011/12/20/3_useful_python_decorator.html#2277951
Complete!