"Python Learning Road -- Decorator for Python Basics"

  A decorator is essentially a function. More intuitively, a decorator is equal to a higher-order function + function nesting + closure. A decorator is a function with a certain basic function, which can be added to other functions. , making other functions more powerful. In addition, the decorator has two important features: 1. It does not change the calling method of the decorated function. 2. It does not change the source code of the decorated function. That is to say, the decorator is to transform other functions on these two features. The function.

A higher-order function means that the parameter received by the function is a function or the return value of the function is a function . Such a function is a higher-order function.

Function nesting means that functions are also defined in the function, which can be nested at multiple levels.

A function closure means that the function inside the function uses the local variables of the outer function.

#Outer wrapper , used to receive the decorated function 
def wrapper(fun):
     #Inner function, used to add basic functions to the decorated function 
    def inner(*args,** kwargs): #Basic
         function code # Call the decorated function and receive the return value 
        result = fun(*args,** kwargs) #return
         the received result return result #equivalent
     to exposing the inner function return inner
        
        
    

@wrapper  # 等价于:foo = wrapper(foo)
def foo(a,b,c=3):print('foo',a,b,c)
   @wrapper
def bar():print('bar') #Call directly, without changing the calling method of the modified function foo(1,2 ) bar()

If the wrapper still needs to pass parameters, you can continue to wrap a layer of functions outside the wrapper

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325123996&siteId=291194637