Python execution order of a plurality of decorator


decorator_a DEF (FUNC):
Print 'in the Get decorator_a'
DEF inner_a (* args, ** kwargs):
Print 'in the Get inner_a'
return FUNC (* args, ** kwargs)
return inner_a

DEF decorator_b (FUNC):
Print 'the Get decorator_b in '
DEF inner_b (* args, ** kwargs):
Print' in the Get inner_b '
return FUNC (* args, ** kwargs)
return inner_b

@decorator_b
@decorator_a
DEF F (X):
Print' in the Get F '
return X 2 *

F (. 1)
performs the code shown above, the final execution result is:

Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_a
Get in f

With our analysis, why is (the flow of execution in a program verification process can be observed through a break point function the way) in this order.

First of all:

1, decorator function is executed immediately after being good decorative function definition.

We put out the last line of code Note:

# F (1)
re-run, you will find the final results of the implementation as follows:

Get in decorator_a
Get in decorator_b
 

Description decorator function is executed immediately after the function definition is a good decoration. And beginning execution order is from the bottom to the decoration. When you call decorator_a, f was decorated inner_a, when calling decorator_b, f was decorated inner_b.

<0x00000000038F15F8 function inner_b at> verifiable print (f), as the execution result: The final performance.

Therefore, as shown in the code of the last executed when f (. 1), f has become inner_b, but in return the inner_b func, but in reality for inner_a, inner_a func f is the ultimate in the return.

So the final call to order

inner_b --->inner_a--->f

Implementation of the results:

Get in inner_b
Get in inner_a
Get in f

 

In practical application scenario, when we use the above two ways to write a decorative method to verify there is no such sign in @login_required, and then verify permissions when enough time @permision_allowed, we use the following order to decorate functions:

@login_required
@permision_allowed
def f()
# Do something
return
总结一下:

When a plurality of decorator decorative function, there is a rule is small to the wrapping (decoration) on the function, performed from top to bottom.

Guess you like

Origin www.cnblogs.com/hyhy904/p/10961996.html