Python learning 09-Functional and functional programming

Source: Internet
Author: User
Tags access properties closure mul

Functional and functional programming
The function returns a value to the caller, while the large-biased function is closer to the process and does not return anything in the actual programming. The language that treats the process as a function usually sets the name of a particular type or value for the function "Nothing is returned." These functions default to the return type of "void" in C, meaning no value is returned. In Python, the corresponding return object type is none.
In short, when the element is not explicitly returned or if none is returned, Python returns a none. The caller receives the object returned by Python, and the object's type is still the same. If the function returns more than one object, Python gathers them and returns them as a single tuple.
Keyword parameters
The concept of keyword arguments is only for function invocation. The idea is to have the caller differentiate the arguments by the name of the parameter in the function call.
Parameter group
Python also allows programmers to execute a function that does not explicitly define parameters by passing a tuple (non-keyword argument) or dictionary (keyword argument) as a parameter group to the function. We will discuss both of these forms in this chapter. Basically, you can put all the parameters into a tuple or a dictionary, just call a function with the container with the parameters, without having to explicitly place them in a function call:
Func (*tuple_grp_nonkw_args, **dict_grp_kw_args)
The Tuple_grp_nonkw_args is a non-keyword parameter group in the form of tuples, and Dict_grp_kw_args is a dictionary with keyword parameters.
function properties
The Function property is another field in Python that uses the period attribute to identify and have namespaces. Notice how we define a document string outside of the function declaration. However, we can still access it at run time as usual. However, you cannot access properties in the declaration of a function. In other words, there is no ' self ' in the function declaration so that you can do things likeDict[' version '] = 0.1 assignment. This is because the body of the function has not been created, but then you have the function object, and you can access its dictionary as we described above. Another free name space!
Internal/inline functions
It is perfectly legal to create another function (object) in the body of a function. This function is called an internal/inline function. Because Python now supports statically nested domains.
Transfer function
When learning a language like C, the concept of a function pointer is a high-level topic, but for functions like other objects, Python is not the case. Functions can be referenced (accessed or other variables as their aliases), as well as parameters passed into the function. and the element functions of container objects, such as lists and dictionaries, have a unique feature that distinguishes it from other objects, which is that functions are callable.
Formal parameters
The formal parameter set of a Python function consists of all the parameters that are passed to the function at the time of invocation, which is exactly paired with the argument list in the function declaration. These parameters include all necessary parameters, keyword parameters, and all parameters that are not necessarily specified when a function call has a default value. The local namespace creates a name for each parameter value. Once the function starts executing, it can access the name.
Position parameters
We are all familiar with the standardized parameters. Positional parameters must be passed in the exact order in which they are defined in the called function. In addition, without any default parameters (see next section), the exact number of arguments to the incoming function (call) must be the same as the number declared. You can pass a keyword argument to a function without positioning it, giving the keyword to match its position in the argument list is granted
. Default parameters
For default parameters, use a predefined default value if no value is supplied for the parameter when the function is called. These definitions are given in the header row of the function declaration. The syntax for declaring variables with default values in Python is that all positional parameters must appear before any of the default parameters.
Variable-length parameters
There may be cases where a function is required to handle a variable number of parameters. A variable-length parameter list can be used. The variable length parameter is not explicitly named in the function declaration, because the number of arguments is unknown before run time (even during run time, the number of arguments for each function call may be different), which is significantly different from the regular parameters (position and default), and the general parameters are named in the function declaration. Because function calls provide both keyword and non-keyword parameter types, python supports variable-length parameters in two ways, and we understand the use ofand *Symbols to specify the elements of tuples and dictionaries as non-keywords as well as methods of keyword parameters. In this section, we will use the same symbol again, but this time in the declaration of the function, it means to receive such a parameter when the function is called. This syntax allows a function to receive parameters that are outside the formal parameters defined in the function declaration.
Non-keyword variable-length parameter (tuple)
When a function is called, all formal parameters (both mandatory and default) assign values to local variables corresponding to the function declaration. The remaining non-keyword parameters are sequentially inserted into a tuple for easy access. Variable-length parameter tuples must be followed by the position and default parameters, and the general syntax for functions with tuples (or non-keyword variable-length arguments) is as follows:
def function_name ([Formal_args,] *vargs_tuple):
"Function_documentation_string"
Function_body_suite
The shape arguments after the asterisk operator is passed as a tuple to the function, and the tuple holds all the "extra" arguments that are passed to the function (which matches all the positions and the named arguments remaining). If no additional parameters are given, the tuple is empty.
Keyword variable parameter (Dictionary)
In the case where we have an indefinite number or an additional set of keywords, the argument is placed in a dictionary with the key in the dictionary as the parameter name and the value as the corresponding argument value. Why must it be a dictionary? Because for each parameter-the name of the parameter and the parameter value-are given in pairs-the dictionary is the best place to save the parameters. This gives the syntax for a function definition that uses a variable parameter dictionary to handle additional keyword parameters:
def function_name ([Formal_args,][*vargst,] **vargsd):
Function_documentation_string Function_body_suite
In order to differentiate between keyword and non-keyword unofficial parameters, a double star is used (). is overloaded so that it is not confused with a power operation. The keyword variable parameter should be the last parameter defined by the function, with * *.
Function-Type programming
Anonymous functions and Lambdapython allow anonymous functions to be created by using the Lambda keyword. Anonymity is because it doesn't need to be declared in a standard way, for example, using DEF statements. (unless assigned to a local variable, such an object will not create a name within any namespace.) However, as functions, they can also have parameters. A complete lambda "statement" represents an expression in which the body of the expression must be placed on the same line as the declaration. Let's now demonstrate the syntax of the anonymous function:
Lambda [arg1[, arg2, ... ArgN]: expression
A lambda expression returns a function object that can be called.
Call a lambda with the appropriate expression to generate a function object that can be used just like any other function. They can be passed to other functions, aliased with additional references, as container objects, and called as callable objects (with parameters, if required). When invoked, these objects generate a result equivalent to the same expression, given the same parameters. They are indistinguishable from functions that return the same computed value as the equivalent expression. , we can assign lambda expressions to a data structure such as lists and tuples, where we can choose which functions can be executed and what the parameters should be based on some input criteria.
Built-in functions apply (), filter (), map (), reduce ()
We'll look at apply (), filter (), map (), and reduce () built-in functions and give some examples of
Examples of how to use them. These functions provide the characteristics of functional programming that can be found in Python. As you might imagine, lambda functions can be well combined with applications that use these functions, because they all carry an executable function object, and lambda expressions provide a mechanism for quickly creating these functions.
Apply (func[, nkw][, KW]) describes the use of optional parameters to invoke func,nkw as a non-keyword parameter, the KW keyword parameter; the return value is the return value of the function call.
Filter (func, SEQ) invokes a Boolean function, Func, to iterate through the elements in each seq; Returns a sequence of elements that enable Func to return a value of ture.
Map (func, seq1[,seq2 ...]) functions func on each element of the given sequence (s) and provides the return value with a list, and if Func is None, Func behaves as an identity function, returning a list of n tuples containing the set of elements in each sequence.
Reduce (func, seq[, Init]) applies the two-tuple function to the elements of the SEQ sequence, each time carrying a pair (previous results and the next sequence element), successively adding the existing result and the rain to the value in the resulting subsequent result, and finally reducing our sequence to a single return value; If the initial value of Init is given, the first comparison will be init and the first sequence element rather than the first two elements of a sequence.
Filter ()
Given a sequence of objects and a "filter" function, each sequence element is filtered through this filter, preserving the object that the function returns as true. The filter function invokes the given Boolean function for each element of the known sequence. Each filter returns a non-0 (true) value element that is added to a list.
If we want to write filter () in pure Python, it might look like this:
def filter (Bool_func, seq):
FILTERED_SEQ = []
For Eachitem in seq:
If Bool_func (Eachitem):
Filtered_seq.append (Eachitem)
Return FILTERED_SEQ

Map ()
The map () built-in function is similar to filter () because it can also handle sequences through functions. However, unlike filter (), map () "Maps" a function call to an element of each sequence and returns a list with all the returned values.
In its simplest form, map () takes a function and a queue, acts on each element of the sequence, and then creates a list of return values that are made up of each function application.

Reduce ()
Reduce uses a two-dollar function (a receive band with two values as input, makes some calculations and then returns a value as output), a sequence, and an optional initializer, which effectively "reduces" the contents of that list to a single value, as if it were a name. In other languages, this concept is also known as folding.
It achieves a single value by taking the first two elements of the sequence and passing them into a two-tuple function. It then uses this value and the next element of the sequence to get another value, and then continues until the entire sequence has been traversed and the final value is computed.
Reduce (func, [1, 2, 3]) =func (func (1, 2), 3)
Partial function Application
The concept of currying combines the concept of functional programming with the default parameters and variable parameters. One with n parameters, the curried function cures the first parameter as a fixed parameter, and returns another n-1 parameter function object, you can create the PFA by using the partial () function in the functional module:
From operator import Add, Mul
From Functools Import Partial
ADD1 = Partial (add, 1)

ADD1 (x) = = Add (1, x)

mul100 = Partial (Mul, +) # mul100 (x) = = Mul (x)
///
ADD1 (10)
11
ADD1 (1)
2

Globa statements
If the name of the global variable is declared in a function body, the name of the global variable can be overwritten by the local variable. Our local bar introduces the global bar to the local scope. In order to explicitly refer to a named global variable, you must use the global statement. The syntax for global is as follows:
Global var1[, var2[, ... Varn]]
Closed Package
If in an intrinsic function, a reference is made to a variable that is in an outer scope (but not at the global scope), then the intrinsic function is considered closure. Variables defined within an external function but referenced or used by an intrinsic function are called free variables. Closures combine the internal function's own code and scope with the function of an external function. The lexical variables of closures do not belong to the global namespace domain or local-but belong to other namespaces, with the "wandering" scope. (Note that this differs from the object because those variables are surviving in the namespace of an object but the closure variable survives in the namespace and scope of a function), closurs is useful for installing calculations, hiding states, and switching freely between function objects and scopes. Closurs is useful in the GUI or in event-driven programming where many APIs support callback functions. In the absolute same way, it is applied to get the database rows and process the data. A callback is a function. Closures are also functions, but they can carry some additional scopes. They are just functions with extra features ... An additional scope.
Now, in many cases, classes are best suited for use. Closures are better suited to the need for a callback function with its own scope, especially if the callback function is small and simple and usually smart. As usual, if you use closures, commenting on your code or using a document string to explain what you're doing is a good idea.
Generator
What is a Python-style generator? The clause says that the generator is a function with a yield statement. A function or subroutine is returned only once, but a generator can pause execution and return an intermediate result-that is, the function of the yield statement, returning a value to the caller and pausing execution. When the next () method of the generator is called, it will proceed exactly from where it left off.
Simple Generator Features
Similar to iterators, the generator works in a different way: when a real return is reached or the function ends without more values returned (when you call Next ()), a Stopiteration exception is thrown.
Some of the reinforcing features are added to the generator, so in addition to next () to get the next generated value, the user can return the value to the generator [Send ()], throw an exception in the generator, and require the generator to exit [Close ()], since the bidirectional action involves a call to send () Code to send a value to the generator (and the value returned by the generator is sent back), the generator comes with an initialized value and counts 1 increments for each call to the generator [next ()]. The user has the option to reset this value if they really want to call send with a new value () instead of calling next (). This generator is always running, and now the yield statement must be an expression, because when you go back to the generator, you may be receiving an incoming object. So if you want to end it, call the Close () method.

Python learning 09-Functional and functional programming

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.