full stack pass through the python decorator Advanced --12-

Decorator with parameters

Decorators use, if you need a parameter to determine whether to enable decorators, you need to pass a parameter to determine whether to enable.

Currently decorator, transfer function names as arguments to external functions, function parameters used inside the function is called, passing the parameters can not be achieved.

Therefore, it is necessary to add a layer nested, to achieve the parameters passed in, the decorator up to three! ! !

import time
from functools import wraps

FLAG = True

def out_warpper(flag):
    def warpper(f):
        @wraps(f)
        def w_in():
            if flag:
                print("this is warp!")
                ret = f()
            else:
                ret = f()
            return ret
        return w_in
    return warpper

# out_warpper = out_warpper(FLAG) → out_warpper = warpper
# func1 = warpper(func1) → func1 = w_in
@out_warpper(FLAG)  # func1
def func1():
    time.sleep(1)
    print("this is func1")

@out_warpper(FLAG)
def func2(): time.sleep(1) print("this is func2") func1() func2()

When the three first rows executed after the @ sign, i.e. out_warpper = out_warpper (FLAG), returns out_warpper = warpper, closure function, able to save the variable flag.

In the @ function name, func1 = warpper (func1), returns func1 = w_in, thereby achieving transmission parameters decorator.

 

A plurality of decorative function decorator

def warper1(f):
    def inner():
        print("begin do inner1!")
        f()
        print("after go inner1!")
    return inner

def warper2(f):
    def inner():
        print("begin do inner2!")
        f()
        print("after go inner2!")
    return inner

def warper3(f):
    def inner():
        print("begin do inner3!")
        f()
        print("after go inner3!")
    return inner

@warper3
@warper2
@warper1
def func():
    print("this is func")


func()

 

 A plurality of decorator decorative function, before the function, from the outermost decorative, perform the function performed innermost → → beginning from the innermost layer, out performed

 

Guess you like

Origin www.cnblogs.com/zxw-xxcsl/p/11721129.html