Python function related

Source: Internet
Author: User

A function in Python is also an object, and a function is a class citizen. Functions can be used as parameters or as return values, which makes the functions in Python flexible. Consider the adorners and closures described in the previous two articles, implemented through inline functions.

Here's a description of what the Python function is about.

Variable length parameters

In the course of programming, you may encounter a case where the number of function parameters is not fixed, then you need to use variable-length function arguments. In the Python function definition, use the * and * * symbols to specify tuples (non-keywords) and dictionaries (keywords) as parameters, respectively.

Non-keyword variable length parameter (tuple)

When the function is called, all parameters are assigned to the corresponding local variables in the function declaration, and the remaining non-keyword parameters are added to a tuple in order for easy access.

Variable-length tuple parameters must be after the position and default parameters, so the function form with variable-length tuple parameters is generally as follows (brackets denote optional parameters) and a variable-length tuple parameter has a "*" Symbol before it:

def FuncName ([Fromal_args,] *Tuple_grp_nonkw_args):    Pass

See an example:

defArgfunc (Positional_arg, keyword_arg="Foo", *Tuple_grp_nonkw_args):Print "Positional_arg:", Positional_argPrint "Keyword_arg:", Keyword_arg forArginchTuple_grp_nonkw_args:Print "Additional_arg:", Arg argfunc (3)PrintArgfunc (3, 4)PrintArgfunc (3, 4,"Hello"," World")

The output of the code is:

Keywords variable length parameter (dictionary)

In addition to the above, Python can support keyword variable-length parameters, and additional keyword parameters are put into a dictionary for use.

The variable-length dictionary parameter must be the last parameter in the function definition, so the function form of the variable-length dictionary parameter is generally as follows (the brackets represent the optional parameters), and the variable-length dictionary parameter has a "* *" symbol before it:

def FuncName ([Fromal_args,] [*tuple_grp_nonkw_args,] * *Dict_grp_kw_args)    :Pass

See an example:

defArgfunc (Positional_arg, keyword_arg="Foo", *tuple_grp_nonkw_args, * *Dict_grp_kw_args):Print "Positional_arg:", Positional_argPrint "Keyword_arg:", Keyword_arg forArginchTuple_grp_nonkw_args:Print "additional Non-keyword arg:", Arg forArgkeyinchDict_grp_kw_args.keys ():Print "additional keyword arg: {'%s ':%s}"%(Argkey, Dict_grp_kw_args[argkey]) Argfunc (3, 4, name="Wilber", age=28)PrintArgfunc (3, 4,"Hello"," World", name="Wilber", age=28)Print

The code output is:

The complete form of a function call is:

Func (Positional_args, Keyword_args, *tuple_grp_nonkw_args, **dict_grp_kw_args)

In the process of use, all parameters are optional, but it should be noted that: the position of the above four parameters is not interchangeable .

anonymous function (lambda)

Python allows you to create anonymous functions using the Lambda keyword, and you can quickly write simple functions with the Lambda keyword.

Use the Lambda keyword in the form of:

Lambda [Arg1 [, Arg2, ... ArgN]: expression

For simple functions that are not often called, it is recommended to use lambda expressions directly for brevity:

Lambda x, y:x+yprint  addnumprint"", Addnum (3, 4)
Several built-in functions

Python can support object-oriented programming well, but you can also experience functional programming through the following built-in functions and lambda expressions in Python.

Filter ()

The complete form of the filter function is filter (func, seq): Calls a Boolean-type function func to iterate through the elements in each SEQ, returning a sequence of elements that enable Func to return a value of ture.

For example, get an odd number within 100:

Print filter (lambda N: (n%2) = = 1, range (100))

Of course, for the example above, you can also use list parsing to implement:

Print  for inch if i%2 = = 1]
Map ()

The complete form of the map function is map (func, seq1 [, seq2 ...]) : The function func acts on each element of a given sequence and provides the return value with a list, and if Func is None, the function is the same as zip ().

Are you dizzy by the description above, or are you looking at an example:

# the func of map is none Print map (none, [4, 5, 6])print map (none, [1, 2, 3], [4, 5, 6#  map for a sequence  Print map (Lambda x:x*2, [4, 5, 6])#  map for multiple series print map (lambda x, y:x + y, [1, 2, 3], [4, 5, 6])

The code output is:

Reduce ()

The complete form of the reduce function is reduce (func, seq [, Init]): Func is a two-tuple function; reduce iterates over each element in the SEQ, iterating over each iteration of the last iteration (using init for the first time, without Init, Executes the Func function with the next element using the first element of the SEQ.

See an example of summing with the reduce function:

print reduce (lambda x, y:x + y, Range ( Lambda x, Y:x + y, ran GE (10), 100)

The output is:

As described above, we can implement a reduce function ourselves:

def xreduce (Bin_func, seq, init=None):    = list (seq)    if is None:        = iseq.pop (0)    Else:        = init    for   in Iseq:        = bin_func (res,obj)    return Res
Summarize

This article describes some of the things that are relevant to Python functions:

    • Variable length parameters
    • anonymous function lambda
    • Built-in function filter (), map (), reduce

Python function related

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.