python closure decorator

Closure

1. What is closure

  • Creating a closure in python generally have three requirements:
    • (1) must have a closure function inline function
    • (2) built-in functions must reference variables of the outer function
    • (3) closure function returns the address (function name) to the nested function
  • Role: You can not modify the target under the premise of the source code, plus function
  • Note: the closure function of the variable to be extended lifecycle

2. Create a function closure

funcOut DEF (): 
    name = 'Jery' 
        
    DEF funcIn (): 
        shorthand # format of the 
        print (f "Name {name} =") 
    return funcIn 
    
F = funcOut () 
F ()

 operation result:

Name = Jery

  

3 determines whether the closure function

  • Closure function relatively common and will be more of a function __closure__ attribute, which defines a tuple of objects used to store all the cell, each cell object holds all the external variables closure.
  • funcIn.__closure__: Return None, the closure function is not
  • Such as:
    funcOut DEF (): 
        name = 'Jery' 
        DEF funcIn (): 
            Print (F "name {name} =") 
        Print (funcIn .__ closure__) 
        Print (funcIn .__ closure __ [0] .cell_contents) # external first variable 
        return funcIn 
    
    F = funcOut () 
    F ()
    

    operation result

    (<cell at 0x000000000272F8B8: str object at 0x00000000026A08B8>,)
    Jery
    姓名 = Jery
    

    Decorator

    1. The nature and role

    • The nature of the decorator
      • Closure function
    • Decorator role:
      • Extend the functionality of the original function without modifying the original function and call mode

    2. Use of the decorator

  • Demand: increase logging to existing features fun1
    • Traditional solutions - with closures
      DEF writeLog (Fn): 
            Print ( "log") 
            Print ( 'Access Method:' + Fn .__ name__) 
      
        DEF funcOut (FUNC): 
            DEF funcIn (): 
                writeLog (FUNC) 
                FUNC () 
            return funcIn 
            
        DEF fun1 (): 
            print ( "using the function. 1") 
            
        DEF fun2 (): 
            print ( "using the function 2") 
        
        fun1 = funcOut (fun1) 
        # decorator (closures) 
        fun1 ()
      
    • operation result:

      Logging 
      access methods: fun1 
      use function 1 
    • Decorator (syntactic sugar) to solve 

        writeLog DEF (Fn): 
            Print ( "log") 
            Print ( 'Access Method:' Fn + .__ name__) 
        
        DEF funcOut (FUNC): 
            DEF funcIn (): 
                writeLog (FUNC) 
                FUNC () 
            return funcIn 
        
        @funcOut 
        DEF fun1 ( ): 
            Print ( "using the function. 1") 
        @funcOut 
        DEF fun2 (): 
            Print ( "using the function 2") 
        
        fun1 () 
        fun2 ()
      

      operation result: 

      Logging 
      access methods: fun1 
      using an feature 
      logging 
      access methods: fun2 
      use function 2 

3. The use of a plurality of decorator

    • Such as:

    • def war1(func):
          print("war 1")
      
          def inner(*args, **kwargs):
              print("======war1 start=====")
              func(*args, **kwargs)  # inner
              print("======war1 end=====")
              return inner
      
      def war2(func):
          print("war2")
      
          def inner(*args, **kwargs):
              print("======war2 start=====")
              func(*args, **kwargs)
              print("======war2 end=====")
          return inner
      
      @war1
      @war2
      def f():
          print("****self****")
      
      f()

    • operation result:
      war2
      war1
      ======war1 start=====
      ======war2 start=====
      ****self****
      ======war2 end=====
      ======war1 end=====  
    • Explanation:
      (. 1) 
      @ WAR1 
      after @ war2 equivalent -> f = war1 (war2 ( f)) 
      wherein war2 (f) is a function, as arguments 
      war2 (f): 
        Print ( "====== WAR2 ===== Start ") 
        Print (" Self **** **** ") 
        Print (" ====== ===== WAR2 End ") 
      
      WAR1 (WAR2 (f)): 
        Print ( "====== WAR1 ================ Start") 
        WAR2 (F) 
        Print ( "====== WAR1 ================ End") 
      (2) 
      F () corresponding to perform -> war1 (war2 (f)) (  )

  4. decorated function has parameters

    • funcOut DEF (Fn): 
          Print ( "funcOut") 
          DEF funcIn (AA, BB): 
              Print ( "funcIn1") 
              Fn (AA, BB) 
              Print ( "funcIn2") 
          return funcIn 
      
      @funcOut 
      DEF Test (A, B): 
          print ( "a =% d, b =% d"% (a, b)) 
      after the # decorator decoration, which is not called directly test method, but the method call func_in 
      test (1,2)
      

       result

    • funcOut
      funcIn1
      a=1,b=2
      funcIn2

  The universal use of the decorator

    • A plurality of decoration can be decorated with different parameters, different values ​​of the function returns
    • Such as:
         funcOut DEF (Fn): 
              # needed parameters, * args, ** kwargs 
              DEF funcIn (* args, ** kwargs): 
                  Print ( "log") 
                  Print ( 'Access Method:' .__ name__ Fn +) 
                  # needed parameters, * args, ** kwargs 
                  # needs return values 
                  return Fn (* args, ** kwargs) 
              return funcIn 
          
          # 1 to be decorated function: no parameters and returns no value 
          @funcOut 
          DEF test1 (): 
              Print ( "test1") 
          test1 () 
          Print ( "---------") 
          # 2 function to be decorated: no parameters, return value 
          @funcOut 
          DEF test2 (): 
              return "the Hello" 
          Print (test2 ()) 
          Print ( "- -------- ") 
          # 3 to be decorated functions: has parameters and returns no value 
          @funcOut 
          DEF Test3 (A):
              Print ( 'D% = A' A%) 
          Test3 (. 1) 
          Print ( "---------") 
          # 3 to be decorated functions: YES key parameters and returns no value 
          @funcOut 
          DEF Test4 (* kwargs *): 
              Print (kwargs) 
          Test4 (A =. 1)
    • result
      Logging 
      access methods: test1 
      test1
       --------- 
      logging 
      access methods: test2 
      the Hello
       --------- 
      logging 
      access methods: Test3 
      A = . 1 
      --------- 
      logging 
      access methods: Test3 
      { ' A ' : . 1 }

       

 

 

      

  

 

Guess you like

Origin www.cnblogs.com/songdanlee/p/11367571.html