09-- closure base python, decorator

1.1  Closures

1, as a function of first-class objects, support assigned to variables, passed as a parameter to other functions, other functions as a return value, supports nested functions, implements __call__ class instance object method may also be used as the function is called

2, s = func -> execution of the function memory address

   s = func () -> function call

 

3, closure: nested function, the internal variable function calls to external functions

         Local variables can make a permanent memory

def  outer():

  a=1             

  def inner (): # closure function

    pritn(a)

  print (inner .__ closuer__) # If the result is cell is a closure function

 

4, a common form of closure   in an internal function for external use function, a function of both the internal variable becomes a

def  outer():

  a = 1 # permanent memory, to prevent other programs change this variable

  def inner (): # closure function

    pritn(a)

    return inner

inn = outer () # function points to a global memory variable

inn()

 

1.2  decorator

1, the role of decorator, do not want to modify the function is called, but still want to increase the functionality of the original function before and after

2. Open Closed Principle

3, the nature of decorators: closure function

. 1  DEF warpper (FUNC):
 2      DEF Inner (* args, ** kwargs):
 . 3          # before the execution of the function do decorated 
. 4          RET = FUNC (* args, ** kwargs)
 . 5          # in the function to be decorated things to do after performing 
6          return RET
 7      return Inner                
wrapper

 

4、functools

from functools import wraps

def wrapper(func):

  @wraps (func) # do not change the name of the function is decorative function

  def inner(*args,**kwargs):

    # Before the function execution garnished do

    ret = func(*args,**kwargs)

    # After being decorated function performs do

    return right

  return inner

 

5, decorator with parameters Layer decorator

Guess you like

Origin www.cnblogs.com/fbug/p/11793021.html