July 17 A Day

1 What is the function of a closure, what kind of conditions to meet the closure function? Please write a common closure function.

A so-called nesting function closure essentially functions and higher-order functions. Let's look at what you want to achieve function closure conditions to be met (indispensable):

1) to be nested function 
2) a variable reference function must be embedded in the closed range (in the external function) is defined - variable internal reference to an external function 
3) external function must return the nested function - an internal function that must return

Action closures: the run state after the program can then continue holding.

We look at an example of a package closure function

Copy the code
def foo():
    num=1
    def add(n):
        nonlocal  num
        num += n
        return num
    return add
f=foo()
print(f(1))  #2
print(f(2))  #4
Copy the code

We can use function closures to implement a function decorator:

We know the function decorator to meet the following conditions: 1, the code can not change the original function. 2, add new features to function. 3, can not change the function is called. Use function closures can do this.

Below we as a function of increasing the statistical function of time:

Copy the code
Time Import 
DEF foo (): 
    the time.sleep (. 3) 
    Print ( 'AAA') 
DEF the decorate (Fun): 
    DEF bibao (): 
        Start the time.time = () 
        Fun () 
        End = the time.time () 
        Print ( ' D is the time spent% '% (Start-End)) 
    return bibao 
foo = the decorate (foo) 
foo ()     
#aaa 
time spent 3
Copy the code

2 What is a recursive function? Using recursive function should pay attention to what?

 

In fact, it calls itself recursively called function:
  default recursion is 1000, because in a recursive when the need to use temporary memory space, performed once
  when one of the above function is still running, so there must be restrictions. Essentially function runs
  will take up stack space to run once add a layer stack space, when too much recursion stack will overflow when

Recursion Note:  

  1. There must be a clear end condition, or to become an infinite loop
  2. Each entry recursive deeper, the scale of the problem should be reduced compared to the previous recursive
  3. recursive implementation of efficiency is not high, too many levels of recursion It may lead to stack overflow

3 implement a recursive function factorial with 10: 10 * 8 * 9 * 7 * 1 ....

 

Guess you like

Origin www.cnblogs.com/zhengyiqun1992/p/11199067.html