python-function and higher order function

Source: Internet
Author: User
Tags closure wrapper

Return by default in the function returns none, if more than one return value is specified, it is encapsulated into a tuple

function parameters

The order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.
def person (name, age=18, *args, City, **kw):

Default parameters must be used immutable objects, if it is a mutable object, the program will run with a logic error!
Variable parameter *args can either be passed directly: Func (1, 2, 3), or the list or tuple can be assembled first, and then passed through *args: Func (* (1, 2, 3));
The keyword parameter **kwargs can either be passed directly: Func (A=1, b=2), or it can be assembled dict, and then passed through **kw: func (**{' a ': 1, ' B ': 2}).
The named keyword parameter is used to limit the name of the parameter that the caller can pass in, as well as providing a default value. Define a named keyword argument in the absence of a mutable parameter
Do not forget to write the delimiter *, otherwise the definition will be the positional parameters. (Unknown parameter?) (so the named keyword argument is a special keyword parameter)

When you have more than one default parameter, you can provide default parameters in order, or you can provide partial default parameters in order, when called.

Scope (Search priority order: LEGB)

Local scope, which is a variable in a function
Enclosing, the local scope of the nested abdominal muscles function, which is the local scope of the ancestor function that contains the function, but not the global
Global variables, which are variables defined at the module level
Built-in, variables in the system fixed module

Recursive functions

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.
The method of solving recursive call stack overflow is optimized by tail recursion, in fact, the effect of tail recursion and loop is the same, so it is possible to think of the loop as a special tail recursive function.
Tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression.
Unfortunately, most programming languages are not optimized for tail recursion, and the Python interpreter is not optimized, so even changing the above fact (n) function to tail recursion can cause the stack to overflow.
Experimental results: Recursion cannot exceed 997 levels?

Any recursive can write the program, the loop can be solved.
The efficiency of recursion is very low.

Lambda expression

Lambda expressions, usually used in situations where a function is required, but do not want to be bothered to name a function, that is, an anonymous function.
# defines a function (lambda expression) preceded by a parameter, a colon followed by a return value, a return value can be an expression; no intermediate procedure
My_lambda = lambda Arg:arg + 1

Higher order functions

By passing functions as parameters, such functions are called higher-order functions, and functional programming refers to this highly abstract programming paradigm.
Map/reduce/filter
Higher-order functions can also return a function as a result value, in addition to the ability to accept functions as parameters.

Closed Package

In general, we define a function. When the function is called, it results in a series of calculations that return the final result.

But sometimes we don't need to sum up at once, but in the later code, what to do if we need to calculate
You can define a 2-layer function, and the outer function returns the function name of the INNER function---this is the closure
Note: When calling the outer function to return the inner function name, the relevant parameters and variables of the outer function are saved in the returned inner layer function.
The inner function returned by each call to the outer function is different, even if the parameter variables of the outer function are exactly the same

Closure function: 2 conditions
1, an intrinsic function is defined in a function
2, the intrinsic function references the variables of the external function

In simple terms, the closure function acts as an intrinsic, but can be called globally.

Decorative Device

Essentially, a decorator (adorner) is a higher-order function that returns a function.
Place the @log at the definition of the now () function, equivalent to executing the statement:

Sometimes it is necessary to copy attributes such as __name__ of the original function into the wrapper () function, otherwise some code that relies on function signatures will be executed in error.
There's no need to write code like wrapper.__name__ = func.__name__, and Python's built-in Functools.wraps is doing it.

Adorner, deepen understanding: Adds a timing function to a function, and also uses the original function to implement
Import time
def outer (AAA):
def inner ():
Start = Time.time ()
AAA ()
Time.sleep (2)
SUN1 = Time.time ()-Start
Return SUN1
return inner
@outer #与abc = outer (ABC) is exactly equivalent, but above the original defined function
DEF ABC ():
Print (' Output is: ')

ABC = OUTER (ABC)
Print (ABC)
Print (ABC ())

Partial function

Functools.partial is helping us to create a biased function,
Int2 = functools.partial (int, base=2)
Equivalent to the following
def int2 (x, base=2):
return int (x, Base)
A simple summary of Functools.partial's function is to fix certain parameters of a function (that is, to set a default value) and return a new function, which is simpler to call the new function.
When a function has too many arguments and needs to be simplified, use functools.partial to create a new function that can fix some of the parameters of the original function, making it easier to invoke.

python-function and higher order function

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.