002_ Part III _[function/higher order function/adorner]

Source: Internet
Author: User

I. Higher-order functions:

    • Sequential sorting

enumerate ([1,2 ,3 , 4, 5]) For idx, item  in enumerate ([1, 2, 3, 4]):     print (IDEX)      print (item) Def sort (*args):     ret = []    for  item in args:        for i, v in  Enumerate (ret):            if item >  v:                 Ret.insert (I,item)                  break        else:             ret.append (item)     return retsort (3, 1, 2,  5) 
    • Reverse order

Def sort (F, *args):     ret = []    for item  in args:        for i, v in enumerate ( RET):            if f:                 if item >= v:                      ret.insert (I,item)                      break             else:                 if item <= v:                     ret.insert (I,item)                      break        else:             ret.append (item)      return retsort (true, 3, 1, 2, 5)
    • Higher-order functions

def sort (Cmp, *args):     ret =  []    for item in args:         for i, v in enumerate (ret):          &NBSP;&NBSP;&NBSP;IF&NBSP;CMP (ITEM,&NBSP;V):                 ret.insert (I, item)                  break        else:             ret.append (item)      RETURN&NBSP;RETDEF&NBSP;CMP1 (x, y): &NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;X&NBSP;>=&NBSP;YDEF&NBSP;CMP2 (x ,  y):     return x <= ysort (cmp1, 3, 1, 2, 5) [5, &NBSP;3,&NBSP;2,&NBSP;1] 

Two. Special functions [built-in functions]:

1.filter the output returns a value of True based on the Boolean return value:

def bigger_5 (x): if x > 5:return True return falsefilter (bigger_5, Range) List (filter (Bigger_5, Range ( )) >[6, 7, 8, 9]

An iterator to the return value in the 2.map output function:

format: Map (func, seq1[, seq2 ...])

Example 1:

def bigger_5 (x): if x > 5:return True return falsemap (bigger_5, Range ()) list (map (bigger_5, Range (10))) & Gt [False, False, False, False, False, False, True, True, true, True]

Example 2:

DEF Inc (X): return x + 1list (Map (inc,[1, 2, 3, 4)) >[2, 3, 4, 5]list (Map (Inc,range (3))) >[1, 2, 3]

Example 3:

List (map (lambda x:x + 1,range (3))) >[1, 2, 3]

Example 4:

A = map (lambda x:x + 1,range (3)) next (a) >1next (a) >2next (a) >3next (a) >stopiteration

3.reduce

Format: Reduce (func, seq[, Init])

The reduce function is a simplification, which is a process in which the last iteration result (the element with the first init, such as the first element of the SEQ without init), executes a two-dollar func function with the next element, each iteration. In the reduce function, init is optional and, if used, is used as the first element of the first iteration.

n = 5print reduce (lambda x, y:x * y, Range (1, n + 1)) # 120
m = 2n = 5print reduce (lambda x, y:x * y, Range (1, n + 1), M) # 240

4.lambda

def sort (CMP, *args): ret = [] for item in Args:for I, V in Enumerate (ret): If CMP (item, v): Ret.insert (i, item) break Else:ret.append (item) return Retsort (lambda x, y : X >= y, 3, 1, 2, 5)

5. function as return value

def make_ic (f=1): Def Inc (X): return x + F return incinc1 = Make_ic (1) inc1 (5) >6

Currying

def bigger (x): def inner_bigger (y): return y > x return inner_biggerlist (Filter (bigger (5), Range ()) > [6, 7, 8, 9]

Three. Functools Library

1.partial [Set default parameters, late can be passed by keyword parameters]

To see if the object is callable:

From Functools import Partialimport pymysqlcallable (bigger_3) bigger_3 = partial (bigger,y=3) connect = partial ( Pymysql.connect, user= ' root ', password= ' xxxx ', database= ' xxxx ', port=3306 ' Connect (host= ' 127.0.0.1 ')

Four. Decorative Device

The essence of an adorner is a function that takes a function as a parameter, returns a function, and usually returns a function that adds a number of statements before and after the incoming function is executed, so called decoration;

    • General Decoration Device

#第一种写法

def Timeit (FN): Def wrap (*args, **kwargs): start = Time.time () ret = fn (*args,**kwargs) print (Time . Time ()-start) return ret return wrapdef sleep (x): Time.sleep (x) Timeit (Sleep) (3)

The second method:

def Timeit (FN): Def wrap (*args, **kwargs): start = Time.time () ret = fn (*args,**kwargs) print (Time . Time ()-start) return ret return wrap@timeitdef sleep (x): Time.sleep (x) sleep (3)
Time.time ()//Get is a natural time time.clock ()//Get is a CPU execution time, occupy CPU time;

2. Decorative Adorner with parameters

import timedef timeit (process_time=false):     cacl = time.clock if process_time else time.time     Def inner_timeit (FN):         def wrap (*args, **kwargs):             start = cacl   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RET&NBSP;=&NBSP;FN (*args, **kwargs)              print (CAcl ()  - start)              return ret         return wrap    return inner_timeit@timeit (True) Def sleep ( x):     time.sleep (x) sleep (3) 
import timedef timeit (process_time=false):     cacl = time.clock if process_time else time.time     Def inner_timeit (FN):         def wrap (*args, **kwargs):             start = cacl ()    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RET&NBSP;=&NBSP;FN (*args, **kwargs)              print (CAcl ()  - start)              return ret         return wrap    return inner_timeitdef sleep (x):     time.sleep (x) Timeit (False) (Sleep) (3)    equivalent  timeit () (Sleep) (3) Timeit (True) (Sleep ) (3) 
import timedef timeit (process_time=false):     cacl = time.clock if process_time else time.time     Def inner_timeit (FN):         def wrap (*args, **kwargs):             start = cacl ()    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;RET&NBSP;=&NBSP;FN (*args, **kwargs)              print (CAcl ()  - start)              return ret         return wrap    return inner_timeit@timeit (True)   or   @timeit ()    or  @timeit (False) def sleep (x):     time.sleep (x) Sleep (3) 
#带参数的装饰器的基本结构def Make_timeit (): Def Timeit (): Def Inner_timeit (FN): Def wrap (*args, **kwargs):     RETURN fn (*args, **kwargs) return wrap return Inner_timeit return Timeit@make_timeit () ()    This is problematic because the syntax parser for Python only supports the correct wording of a parameter with the following time_2 = Make_timeit () @time_2 () or time_2 = Make_timeit () () @time_2def fn (): Pass

3. Practical Application of adorners:

Flask used a lot of decorations to do the routing.

[Flask.pocoo.org]


#利用装饰器进行权限控制

def check (allows): Def deco (FN): Def wrap (username, *args, **kwargs): If username in allows: RETURN fn (username, *args, **kwargs)//This line needs to correspond to wrap this line one by one return "not allow" return wrap re Turn Deco@check (["Comyn", "Mage"]) def private (username): print ("congratulation") Private ("Comyn")

4. Word document for function [wraps]:

def test ():         "         this is test          @return  None         '          passhelp (test) >help on function test in module __main__: Test ()     this is test     @return  noneimport time 
Def timeit (process_time=false):     cacl = time.clock if process_ Time else time.time    def inner_timeit (FN):         def wrap (*args, **kwargs):             start = cacl ()             &NBSP;RET&NBSP;=&NBSP;FN (*args, **kwargs)              print (CAcl ()  - start)              return ret        wrap.__name__ = fn.__name__         wrap.__doc__ = fn.__doc__         return wrap    return inner_timeit@timeit (True)    or  @timeit ()    or  @timeit (False) def sleep (x):     "         this is test         ' Sleep.__name__help ( Sleep

# Word document using wraps to implement functions

Import timefrom functools import wrapsdef timeit (Process_time=false):     cacl = time.clock if process_time else time.time          @wraps ()     def inner_timeit (FN):         def wrap (*args, **kwargs):             start = cacl ()           &NBSP;&NBSP;&NBSP;RET&NBSP;=&NBSP;FN (*args, **kwargs)              print (CAcl ()  - start)              return ret        return wrap     return inner_timeit@timeit (True)   or  @timeit ()    or @ Timeit (False) def sleep (x):      '         this is test          ' Sleep.__name__help (sleep)


This article from "Technical Side dishes" blog, declined reprint!

002_ Part III _[function/higher order function/adorner]

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.