Python Learning note-day05-The first part (again on adorners) (recursion)

Source: Internet
Author: User
Tags define function

Today, it took more than a day to learn how to install the X weapon---decorator,

To talk about the use of adorners in detail.

Let's just say that before you learn the decorator you have to figure out what a function is. An adorner is a wrapper over a function, which, in a metaphor, is:

Suppose there is a box a, the outside of box A and a large box, the outside of the big Box also called a, after looking for the small box A, the first to find out the big box A, open the outside of the big box A after opening the inside of the small box A, this is the adorner.


    1. Adorners are also a function, at least two layers

Def outter (func):                 #定义函数  outter, the parameter is the function name of a function, here is Func,    def inner ():                      #定义函数inner         print  "Before"          tmp = func ()                 #执行函数func (),  here func is the parameter of Outter         print  "after"         return tmp    return inner                   #    Return function name inner@outter                               #  to the following function plus adorners, here is a syntax for Sugar def foo ():                              #  define function foo    print  " Foo "foo ()                                        #指定函数foo (), where the   foo ()   function is an adorner-trimmed function

Output:

Before
Foo
After

2. When executing the above code, the function name Foo of the decorated function foo () is the parameter, i.e. Outter (foo), the return value of the Outter function, and the function name of the decorated function is re-assigned.


3. Adorners can be decorated with N (n>=0) parameters of the function, for the function with different number of parameters, the adorner uses dynamic parameters to deal with the problem of the parameter, we modify the above example, modified to solve the problem of the transfer of parameters:

4. The return value of the function, if the function has a return value, we need to consider how the return value of the function is passed back, directly return the result of the function to return it:

def outter (func): Def inner (*args,**kwargs): #设置参数 print "before" TMP = func (*args,**kwargs) #设置参数, which The parameters in the inner are the same as the parameters of the print "after" return TMP # Variable TMP value is the execution result of Func (*args,**kwargs), returning the return value of the decorated function return I Nner@outterdef foo (arg,*args): Print arg, "---", argsfoo (1,2,3,4)

5. Multi-Adorner

A function can be decorated by multiple functions at the same time, the function is decorated by multiple adorners, the effect is similar to the Russian set of dolls.

def W1 (fun): Def inner (): print "W1,before" Fun () print "W1,after" return Innerdef W2 (fun): def inner (): print "W2,before" Fun () print "W2,after" return inner@w2@w1def foo (): print "foo" Foo ()

Execution results

W2,beforew1,beforefoow1,afterw2,after


6. Decorative Adorner with parameters (at least three layers)

When adding an adorner to a function, the adorner also has parameters with the following code:

def Filter (Before_func,after_func): Pass@filter (before, after) def Index (Request,kargs): Pass

Now on the full code, then explain:

Def before (Request,kargs):   #1   load before function to memory                                #14   Execution Functions  Before                                  print  ' before '       #15   EXECUTE PRINT statement      Def after (Request,kargs):  #2   load after to memory                                #21   Execute after function                                   print  ' after '      #22   Execute PRINT statement     def filter (before_func,after_func):  #3   Load function filter to memory                                        #5   Executive Decorators filter                                          def outer (Main_func):             #6   Load function outer to memory                                        #8   Execute function outer                                              def  wrapper (Request,kargs):   #9    load function wrapper                                        #12   Execute function wrapper                                                    before_result = before_func (Request, Kargs)    #13   Assign value to Before_result                  &nbSp;       if (Before_result != none):  # 16  Execute if statement, here to judge false                  return before_result                             main_result =  Main_func (Request,kargs)   #17   assigning variables Main_result                          if (main_result  != none):         #19   Execute if statement, which is judged false                               return main_result             After_result = after_func (Request,kargs)   #20   Assign value to After_result                           if (after_result != none):   #23   Execute if statement,  here to judge false                  return after_result                          return wrapper   #10   Returns the return value of the function outer,warapper             return outer   #7   Returns the return value of the filter function, that is, function name outer      @Filter (before, after)    #4   Discover decorators filter,                           #17   Executive FiltER (before, after)                          def index (Request,kargs):     print  ' index '       #18   Execute PRINT statement     index ("Quest0" , "Kwargs0")    #11   Execute function  index


###############################################################


Recursive

Recursive algorithm is an algorithm that calls itself directly or indirectly.

In a metaphor, that's the way it goes.

Once there was a mountain, there is a temple in the mountain, there is an old monk in the temple, the old monk said to the little monk: there once was a mountain, there is a temple on the mountain, there is an old monk in the temple, the old monk said to the little monk: there once was a mountain, there is a temple on the mountain, there is an old monk in the temple

Recursive algorithm can effectively solve a large class of problems, such as the classic Hanoi (also known as Hanoi) problem,

The recursive algorithm is characterized by

1. Calling itself in a function or procedure

2. There must be a clear condition for recursion to end

3. Simple algorithm, but low efficiency

4. Easy to cause stack overflow (because in the execution process, each layer of return points, local variables, etc. to open up stacks to store)


To implement the Fibonacci sequence, for example:

def fib (A1,A2): # print A1,A2, a3=a1+a2 if a3>100: #这里加入了结束条件, if not, will form a dead loop return A3 # Print a 3, return fib (A2,A3) # fib (a2,a3) print fib (0,1)


Recursion can be converted to and from while.

The code in the above code is implemented with a while loop:

A1,A2 = 0,1
While a1<200:
Print A1
A2=a1+a2
A1=a2-a1



http://timesnotes.blog.51cto.com/1079212/1716574

http://www.timesnotes.com/?p=114


This article is from the "'ll Notes" blog, so be sure to keep this source http://timesnotes.blog.51cto.com/1079212/1716574

Python Learning note-day05-The first part (again on adorners) (recursive)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.