Many people make the decorator very complicated, in fact, the essence is very simple.
First of all, what is an adorner? In the code it is found that the @xxx hat is the adorner.
So how do you define an adorner yourself?
in fact, any callable that receive a parameter can be used to make adorners, such as functions and classes. For the sake of convenience, the following examples are illustrated with functions.
1 def deco (func):return 1
Here, Deco can do decorators.
1 @deco 2 def F (args):pass
"Hats" is actually called, the Hat on who (a function definition) head, it means who will be called as arguments, and then assigned to a variable with the same name .
The above example is equivalent to F = Deco (f). The result is that the function f becomes 1.
Of course, we do not use adorners to return 1. Our main purpose is "to maintain the function of the original functions and add additional Functions".
Then we define an adorner, "receive a function as a parameter and return a function."
1 def return
This way we can add code tampering enhancements before return func, but what if we still need to tamper with the Func? also need to capture the func parameter args. So we wrap it with another function.
Because the function is a class citizen, we can define the function inside the function. This is the most commonly used form of definition for adorners, in the following form
1 def Deco (func): 2 def Newfunc (*args, * *Kwargs) :3 func (*args, * *Kwargs )4 return
Where *args, **kwargs is used to capture parameters.
We need to output the information before and after the function executes, just
1 ef Deco (func): 2 def newfunc (*args, **kwargs):
3 print '
After understanding the essence, what a mess of "adorners without parameters"/"Adorner with parameters"/"function Adorner"/"Class decorator"/"multiple adorners"/"Why @route can automatically collect URLs" and so on are all appearances.
An adorner with parameters?
You can think of it as a function call.
Transferred from: http://blog.csdn.net/handsomekang/article/details/39997163
The essence of the elegant Python-decorator