Decorator function (b)

Advanced decorator

1. decorator with parameters
is the introduction of a new parameter on the basis of the original decorator

Multi-layer function sets, a multi-pass parameter determines whether the added functionality, but using multiple closures pass a parameter

And decorators of the same principle, this time to the outside world to pass parameters in the original decorator function on and then set the layer functions to achieve

Now outermost decorative role in this space is a function only of the structure in nested function introduces a new local variable, and the value of the variable is introduced from the outside

At this time, a multi-layer nested functions, since each of the function name in parentheses is the one called, so separated and put back @ @ look into two parts, each of the function name in parentheses is the one called, so to @ @ separates into two parts back and see

import time
FLAGE = False
def timmer_out(flag):
    def timmer(func):
        def inner(*args,**kwargs):
            if flag:
                start = time.time()
                ret = func(*args,**kwargs)
                than = time.time ()
                 quality (end- start)
                 Return entitled
             presence :
                right = func (* args, ** kwargs)
                 return right
         return inner
     return Timmer
 # Timmer = timmer_out (flake) 
@timmer_out (flake)     # Wahaha = Timmer (Wahaha) 
def Wahaha ():
    time.sleep ( 0.1 )
     print ( ' wahahahahahaha ' )

@timmer_out (flake)
DEF erguotou ():
    time.sleep(0.1)
    print('erguotoutoutou')

Wahaha ()
erguotou ()

Plus decorator @wraps (func) does not affect the original function name before the inner, but the need to introduce this function module from functools

If a layer of decorative function, a function name is taken out of operation should not real name, is obtained inside the decorator 'inner

 

2. Decorative plurality decorator same function

A top
following a
first implementation of the above front, and then the front, rear and then the next, and then the rear
doll execution structure, above the outermost circle.
Principle: the real execution order must be recent decorator function, recent decorator function passed in the function name, return value as a parameter decorator away for execution.

Execution results as shown

The user can record the landing, but also to calculate the execution time, but it must be a logical order of execution of two things must be clear.

Guess you like

Origin www.cnblogs.com/shachengcc1/p/11166131.html