Python's functional programming-incoming functions, sorting algorithms, functions as return values, anonymous functions, partial functions, adorners

Source: Internet
Author: User

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design. Incoming functionThe function itself can also be used as a parameter. Python's built-in MapReduce function. (from Google, then Doug this guy was open source and became the computing model in today's hottest hadoop for big data---MapReduce) Let's look at map first. map()The function receives two parameters, one is a function, the other is a sequence, mapFunctions the passed-in function sequentially to each element of the sequence and returns the result as a new list.
 1  #   2  def   F (x):  3  return  x*x  4  l = [1,2,3,4,5,6,7,8 5  print  map (F, L) #  [1, 4, 9, +----------]  

Notice the functions f we define . When we write f , it refers to the function object itself, when we write f(1) , referring to the call F function, and passed in Parameter 1, expecting to return the result 1.

Therefore, map() the first parameter passed in is the f function object itself.

Functions such as functions that map() can receive functions as arguments are called higher-order functions (Higher-order function).

Let's look at the usage of reduce. Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
1 #use reduce to complete a sum calculation2 defAdd (x, y):3     returnx+y4 PrintReduce (ADD, L)# $5  6 #converting a numeric string to an integer using the MapReduce implementation7 defStr2Int (s):8     deffn (x, y):9         returnX * 10 +yTen     defChar2num (s): One         return{'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9'8 {}[s] A     returnreduce (FN, map (Char2num, s)) - PrintStr2Int ('12345')

Sorting algorithms

Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the two elements. As a rule, for two elements xAnd y, if you think x < y, The return -1, if you think x == y, The return 0, if you think x > y, The return 1, so that the sorting algorithm does not care about the specific comparison process, but is based on the comparison of direct ordering. Python built-in sorted()function to sort the list.
 1  #   2  def   MyOrder (x, y):  3  if  x > y:  4  return  -15  elif  x< y:  6  7  else : return   0  8  print  sorted (L, MyOrder) 

function as return value

Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.
1 #A summation function that takes a function as the return value2 defLaz_sum (*args):3     defsum ():4Ax =05          forNinchargs:6Ax = ax +N7         returnAx8     returnsum9  TenFF = Laz_sum (*l)#<function Add at 0x021448b0> One PrintFF ()# $

In This example, we are in the function lazy_sum The function sum is also defined in the , and the intrinsic function sum external Functions lazy_sum can be referenced the parameters and local variables, when lazy_sum return function sum , the associated parameters and variables are stored in the returned function, a program structure called closure (Closure) that has great power.

Note again that when we call lazy_sum() , each call returns a new function, even if the same parameter is passed in:

>>> f1 = lazy_sum(1, 3, 5, 7, 9)>>> f2 = lazy_sum(1, 3, 5, 7, 9)>>> f1==f2False

f1()and f2() the results of the call are not affected.

Anonymous FunctionsWhen we pass in a function, there are times when we don't need to explicitly define a function, and it's easier to pass in an anonymous function directly. In Python, there is a limited amount of support for anonymous functions. or to map()function as an example, when calculating f (x) =x2, in addition to defining a f(x)function, you can also pass in the anonymous function directly:#使用匿名函数实现平方计算Print map (lambda x:x*x,l)

The anonymous function lambda x: x * x is actually:

def f(x):    return x * x

The keyword lambda represents an anonymous function, preceded by a colon, that x represents a function parameter.

The anonymous function has a restriction that there can be only one expression, without writing return , and the return value is the result of that expression.

。 In addition, the anonymous function is also a function object, you can assign the anonymous function to a variable, and then use the variable to invoke the function:

>>> f = lambda x: x * x>>> f<function <lambda> at 0x10453d7d0>>>> f(5)25

Similarly, anonymous functions can be returned as return values, such as:

def build(x, y):    return lambda: x * x + y * y
Decorative DeviceBecause a function is also an object, and a function object can be assigned to a variable, the function can also be called through a variable. A function object has a __name__property, you can get the name of the function. Now, let's say we want to enhance now()Functions, such as automatically printing logs before and after a function call, but do not want to modify now()The definition of a function, a way of dynamically adding functionality during the run of the code, is called an "adorner" (Decorator). Essentially, decorator is a higher-order function that returns a function. #实现一个装饰器, print the log file
1 deflog (func):2     defWrapper (*args,**kw):3         Print 'Run the%s () method:'% func.__name__4         returnFunc (*args, * *kw)5     returnwrapper6 @log7 defNow ():8     Print "2014-11-13"9  TenNow ()#called

observe the above log , because it is a decorator, it takes a function as an argument and returns a function. We're going to use Python's @ syntax to place the decorator at the definition of the function.

Put @log to now() the definition of the function, the equivalent of executing a statement:

now = log(now)
wrapper()The parameter definition of the function is (*args, **kw)So wrapper()The function can accept calls of arbitrary arguments. In wrapper()function, the log is printed first and the original function is called immediately thereafter.

Because we're talking about functions and objects, and it has __name__ properties like that, but you see the functions after the decorator decoration, and they __name__ have changed from the original ‘now‘ ‘wrapper‘ :

>>> now.__name__‘wrapper‘

Because the name of the function returned is the same, wrapper() ‘wrapper‘ so you need to copy the properties of the original function __name__ into the wrapper() function, otherwise, some code that relies on the function signature will be executed with an error.

Python is built to functools.wraps do this, so a complete decorator is written as follows:

1 ImportFunctools2 3 deflog (func):4 @functools. Wraps (func)5     defWrapper (*args, * *kw):6         Print 'Call %s ():'% func.__name__7         returnFunc (*args, * *kw)8     returnWrapper

or for decorator with parameters:

1 ImportFunctools2 3 deflog (text):4     defDecorator (func):5 @functools. Wraps (func)6         defWrapper (*args, * *kw):7             Print '%s%s ():'% (text, func.)__name__)8             returnFunc (*args, * *kw)9         returnwrapperTen     returnDecorator

import functoolsis import functools module. The concept of the module is explained later. Now, just remember to add it to the wrapper() front of the definition @functools.wraps(func) .

Partial functionPython's functoolsThe module provides a number of useful functions, one of which is the partial function. It is important to note that the partial function here is not the same as the partial function in mathematical sense. Main functions: functools.partialis to fix some parameters of a function (that is, to set a default value) and return a new function, which is simpler to call the new function. For example, int () is the default conversion of a string to a decimal integer, so what if I want to convert to binary by default?

To create a new function directly using the following code int2 :

>>> import functools>>> int2 = functools.partial(int, base=2)>>> int2(‘1000000‘)64>>> int2(‘1010101‘)85
Finally, when you create a partial function, you fix the arguments from right to left, that is, for the function f(a1, a2, a3), can be fixed a3, you can also fix a3And a2, you can also fix a3a2And a1, but do not jump fixed, such as only fixed a1And a3, put a2It's missing. If you do this, it is more complicated to call the new function.

Python's functional programming-incoming functions, sorting algorithms, functions as return values, anonymous functions, partial functions, adorners

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.