Python3 Quick Reference - Python Basics -> Decorators and Generators for Functional Programming

decorator


 

1. Quick Check Notes

# -- Function decorator: The runtime declaration of the function behind it consists of the @ symbol and the "metafunction" (metafunction) immediately following it   
        @staticmethod  
         def smeth(x): print (x)  
     #equivalent to:   
        def smeth(x): print (x)  
        smeth = staticmethod(smeth)  

Definition: A way to dynamically add functionality during code execution, called a "Decorator"

Classic example:

# -*- coding:utf-8 -*- 
import time
 def timer(func): #Pass the memory address of the decorated function ceshi to func 
    def deco(*args,** kwargs):
        start_time = time.time()
        func(*args,**kwargs)
        stop_time = time.time()
         print ( ' Test function running time ' ,(stop_time- start_time))
     return deco #Return the memory address of deco

@timer
def ceshi(a):
    time.sleep( 3 )
     print ( ' Test %s ' % a)
ceshi( ' decorator ' )

2. Principles: ① The source code of the decorated function cannot be modified; ② The calling method of the decorated function cannot be modified

3. Implement the skill reserve of decorators

① The function itself is a variable

② Higher-order functions, pass a function name as an argument to another function

③ Nested functions

 

Reference: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318435599930270c0381a3b44db991cd6d858064ac0000

 

 

Builder


 

1. Quick Check Notes

# -- Generator function: yield VS return   
    def gensquare(N):  
         for i in range(N):  
             yield i** 2                  #Suspended state can be restored to the current state   
    for i in gensquare(5):               #Use Method   
        print (i, end = '  ' )              # [0, 1, 4, 9, 16]   
    x = gensquare(2)                     # x is a generated object   
    next(x)                              # same as x.__next__() returns 0   
    next( x)                              #equivalent to x.__next__() returns 1  
    next(x)                              #equivalent to x.__next__() throws an exception StopIteration  
      
# -- Generator expression: parentheses for list comprehension   
    G = (x ** 2 for x in range(3))       # use parentheses to create a generator object with the desired result   
    next(G), next(G ), next(G)            # is the same as the return value of the generator function in the above   
    # (1) The generator (generator function/generator expression) is a single iterative object   
    G = (x ** 2 for x in range( 4 ))  
    I1 = iter(G)                         #Here in fact iter(G) = G   
    next(I1) #output                             0 next   
    (G)                              #output 1   
    next(I1) #output                             4 # (   2 ) The generator does not retain the iterative result   
    gen = (i for i in range(4 ))  
 ​​in gen                             #return True   in gen                             #return True   in gen                             #
    

Returns False. In fact, when 2 is detected, 1 is no longer in the generator, that is, 1 has been iterated, and similarly 2 and 3 are no longer there.  

2. Generator Expressions

Limitations: only suitable for simple algorithms

Example: 

test = (x**2 for x in range(1,10))
print(next(test))
print(test.__next__())

 

 

3. The generator function yield

Example of printing the Fibonacci function:

def fib(max):
    a,b,n = 1,1,0
    while n<max:
        yield b
        a,b = b,a+b
        n+=1
    return b
test = fib(10)
print(test.__next__())
print(next(test))
for i in test:
    print(i)

 

Guess you like

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