Python functions and functional programming

Source: Internet
Author: User

Python functions and functional programming

FunctionIt is a programming method that structured or procedural the program logic.Functions and processesIn contrast, both are callable entities. However, in the traditional sense, a function or a "black box" may not contain any input parameter. After some processing, a return value is returned to the caller, the process is a simple, special function with no return value. In fact, the python process is a function, because if there is no explicit return value in the function, the interpreter will implicitly return the default value None.

1Function Definition

 

def foo([argument-list]):“function_document_string”foo_suite

 

Function Definition keywordsDefFollowed by the function name, followed by an optional parameter list in parentheses. The parameter type is dynamic and does not need to be specified. You only need to write the parameter name, then there is the function body (including a optional but strongly recommended document string, the first string without a value after the function declaration; of course, after the function is created, you can also use_ Doc __Add a function document string outside the function). The return statement is optional. By default, None is returned. When multiple objects are returned, it is actually a single tuples.

In other languages, function declarations and definitions such as C/C ++ are generally separated, but python functions regard the two as one and supportForward reference.

Python supportEmbedded FunctionsThat is, define a function in def within the function. Such a function isClosure. When an embedded function uses a local variable of an external function rather than a global variable, this variable is a free variable.Func_closureAttribute access.

If the local variables in the function body have the same name as the global variables in the function bodyGlobalAfter the keyword is modified, the global variable is overwritten. Otherwise, the global variable is still the original value.

Python Function SupportRecursionCall, that is, you can call yourself.

2, Function call

Function calling through the operator-parentheses()You can also assign the function name to another variable. Then, you can call the function through the new variable.

foo()result = foo()foo2 = foofoo2()result2 = foo2()

3, Function parameters

When calling a function,Parameter orderInput parameters in sequence in the function declaration. If this rule is not followed, the parameter must be assigned a value using the parameter name. This is the location requirement of the function parameter.

Like C/C ++, python functions also supportDefault parameters.

Function NameIt can also be used as a parameter to input a function. Unlike other parameters, a function can be called.

The following is an example where the default parameters and parameters are function names:GrabWeb. py

This script captures the first and last non-empty lines of HTML from the Baidu homepage.

#!/usr/bin/env pythonfrom urllib import urlretrievedef firstNonBlank(lines):for eachLine in lines:if not eachLine.strip():continueelse:return eachLinedef firstLast(webpage):f = open(webpage)lines = f.readlines()f.close()print firstNonBlank(lines),lines.reverse()print firstNonBlank(lines),def download(url = 'http://www.baidu.com', process = firstLast):try:retval = urlretrieve(url)[0]except IOError:retval = Noneif retval:print retvalprocess(retval)if __name__ == '__main__':download()

FunctionParameter Group--

Python allows you to execute a function without explicitly defining parameters by passing the tuples (non-Keyword parameters) or dictionaries (keyword parameters) as parameter groups to the function.

Func (positional_args, keyword_args, * tuple_grp_nonkw_args, ** dict_grp_kw_args)

Where, tuple_grp_nonkw_args (Note the preceding*Is a non-Keyword parameter group in the form of tuples, dict_grp_kw_args (Note the preceding**Is a dictionary containing keyword parameters. It also includes location parameters and keyword parameters. All parameters in this syntax are optional. This parameter group can effectively replace the apply () built-in function.

The following is an example of using a parameter group:MathGame. py

Randomly select a number and an arithmetic function, display the problem, and verify the result. After three wrong attempts, the result is displayed. After the user inputs a correct answer, the operation continues.

#!/usr/bin/env pythonfrom operator import add, subfrom random import randint, choiceops = {'+': add, '-': sub}MAXTRIES = 2def doprob():op = choice('+-')nums = [randint(1, 10) for i in range(2)]nums.sort(reverse = True)ans = ops[op](*nums)pr = '%d %s %d = ' %(nums[0], op, nums[1])oops = 0while True:try:if int(raw_input(pr)) == ans:print 'correct'breakif oops == MAXTRIES:print 'answer\n%s%d' %(pr, ans)else:print 'incorrect... try again'oops += 1except (KeyboardInterrupt, \EOFError, ValueError):print 'invalid input... try again'def main():while True:doprob()try:opt = raw_input('Again? [y]').lower()if opt and opt[0] == 'n':breakexcept (KeyboardInterrupt, EOFError):breakif __name__ == '__main__':main()

Variable Length ParameterIt is also supported in python and corresponds to the function parameter group mentioned above. The variable length parameter of a non-Keyword is a tuple, represented by *, and the variable length parameter of a keyword is a dictionary, it is represented by ** (not 'distinct' operation, which has been reloaded, in the function parameter list, the sequence is the common location parameter, default parameter, non-Keyword variable length parameter *, and keyword variable length parameter **. the following example:

def function(arg, arg2 = 'default', *aTuple, **aDict):pass

4Function decorators@

DecoratorIt is a modifier on the function call. The syntax uses@Followed by the modifier name and optional parameters, followed by the modifier's function. The decorator Can be stacked like a function call. The following is a common example:

@decorator2(deco_arg)@decorator1def function(): pass

The two decorator mentioned above, one without parameters and one with parameters, are equivalent to the following usage:

def function(): passfunction = decorator2(deco_arg)(decrator1(function))

In essence, the decorator introduces the name of a java developerAOPThe concept of Aspect-oriented programming can be used to introduce logs, add timing logic to detect functions, and add transaction capabilities to functions.

The following is an example of a decoration device:DecoratorEx. py

The decorator has an embedded function (closure) used to display the function execution time, which is a timestamp decoration.

#!/usr/bin/env pythonfrom time import ctime, sleepdef tsfunc(func):def wrappedFunc():print '[%s] %s() called' %(ctime(), func.__name__)return func()return wrappedFunc@tsfuncdef foo():passif __name__ == '__main__':foo()sleep(2)for i in range(2):sleep(1)foo()

The execution result is as follows (the time is consistent with the Code intent ):

[Fri May 29 10:50:50 2015] foo() called[Fri May 29 10:50:53 2015] foo() called[Fri May 29 10:50:54 2015] foo() called

The above example uses the closure and decorator, which is relatively simple. The following shows a complicated example, adding a parameter to the decorator. This parameter determines which closure will be called, that is, the decoration content is executed before or after the function is called.

#!/usr/bin/env pythonfrom time import timedef logged(when):def log(f, *args, **kargs):print '''Called:function: %sargs: %rkargs: %r''' %(f, args, kargs)def pre_logged(f):def wrapper(*args, **kargs):log(f, *args, **kargs)return f(*args, **kargs)return wrapperdef post_logged(f):def wrapper(*args, **kargs):now = time()try:return f(*args, **kargs)finally:log(f, *args, **kargs)print "time delta: %s" %(time() - now)return wrappertry:return {"pre": pre_logged, "post": post_logged}[when]except KeyError, e:raise ValueError(e), 'must be "pre" or "post"'@logged("post")def post_hello(name):print "Hello, ", name@logged("pre")def pre_hello(name):print "Hello, ", nameif __name__ == '__main__':pre_hello("World!")print '-' * 50post_hello("Python!")

The execution result is as follows:

 

Called:function: 
 
  args: ('World!',)kargs: {}Hello,  World!--------------------------------------------------Hello,  Python!Called:function: 
  
   args: ('Python!',)kargs: {}time delta: 9.89437103271e-05
  
 

5,LambdaExpression

LambdaThe expression creates an anonymous function and returns the callable function object. The syntax is as follows:

Labmbda [arguments]: expression

6Function programming built-in functions

Apply (func [, nkw] [, kw]): use an optional parameter to call func. nkw is a non-Keyword parameter. kw is a keyword parameter. The return value is the return value of function call. This function is gradually eliminated in later python versions.

Filter (func, seq): Call a Boolean function func to iterate over the elements in each seq and return a list of elements that make func return true.

Map (func, seq1 [, seq2...]): function func is used to act on each element of a given sequence, and a list is used to provide the return value. If func is None, func is represented as an identity function, returns a list of n tuples containing the collection of elements in each sequence.

Reduce (func, seq [, init]): acts binary functions on the elements of the seq sequence, each carrying a pair (previous results and the next sequence element ), continuously apply the existing results and the next value to the subsequent results, and finally reduce our sequence into a single return value. If the initial value init is given, the first comparison will be init and the first sequence element, rather than the first two elements of the sequence.

The above four functions are often used together with lambda expressions, and their func parameter is set to a lambda expression.

7Partial function applications

Partial function applicationsPFA combines functional programming, default parameters, and variable parameters.FunctoolsModulePartial ()Function.

>>> from operator import add>>> from functools import partial>>> add1 = partial(add, 1)>>> add1(10)11>>> add1(100)101

The above add1 () receives a parameter and adds it to the default fixed 1. add1 (x) is equivalent to add (1, x ).

 

 

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.