Functions and anonymous functions

First, the function

In computer science, the program function is responsible for completing a specific task code units, has a certain independence.

1. Definition Function

In Python, function when required to meet the definition of such rules:

  • Boot using the keyword def;
  • Is the name of a function behind def, in parentheses are function parameters, different parameters comma "," separated, the parameters may be empty, but the brackets can not be omitted;
  • Function block to indent;
  • A pair of "" "character string as a function of instructions contained, for purposes of interpretation function may be omitted;
  • Keyword return to return a specific value, if omitted, returns None.

For example, we define a simple addition function that takes two variables x and y, x and y is calculated, and ah, and returns the value of a:

def add(x,y):
    """Add two numbers"""
    a = x + y
    return  a

2. call function

After you define a good function, the function will not be executed automatically. We need to call it in order to implement the relevant content.

Function call using the function name in the form of parentheses, brackets in the parameter, the parameter is divided into formal and actual parameters, a parameter defining a function, a function call arguments.

DEF the Add (X, Y):           # parameter 
    "" " the Add TWO Numbers " "" 
    A = X + Y
     return   A 
the Add ( 1,2)          # call method, argument

When the number of parameters passed in does not match the actual error.

When the incoming parameter does not support the addition, it will be given.

An incoming parameters, Python provides two modes, a first order parameter is passed, the other is using a key - value pattern, according to the parameter name parameter passed:

DEF the Add (X, Y):
     "" " the Add TWO Numbers " "" 
    A = X + Y
     return   A 
the Add (X =. 1, Y = 2)      # key - value mode, the order may be reversed

You can also use both modes together, the premise is key - value mode parameters must be in the right mode, otherwise it will error:

def add(x,y):
    """Add two numbers"""
    a = x + y
    return  a
add(1,y=2)          #add(x=1,2)会报错

3. With default function arguments

We can set default values ​​for function parameters, default parameters need to be set in the definition, the definition, all parameters with default values ​​must be placed behind parameters without default values:

DEF handle (X, type = ' None ' ):
     Print (X, type) 
handle ( ' Hello ' )          # results: hello, None 
handle ( ' Hello ' , ' MySQL ' )    # may cover, the result is: hello, mysql

4. The parameters

Parameter set using an asterisk "*" or two asterisks defining a function "**" is achieved.

Use an asterisk of the parameters used are as follows:

DEF Test (X, * args):     
     Print (X)            # results:. 1 
    Print (args)        # result: (2,. 3,. 4,. 5,. 6) 
    Print (args [0])    # results: 2 
Test (1,2,3,4,5,6)

* Args parameter is a variable number of arguments, we can see it as a tuple.

When calling test (1,2,3,4,5,6), the first parameter passed to a x, a composition of the remaining parameters passed tuple args, therefore, args values ​​(2,3, 4,5,6).

Two asterisks parameters used are as follows:

DEF Test (X, ** kW args):
     Print (X)       # results:. 1 
    Print (kwargs)      # result: { 'Y': 2, 'Z':. 3, 'W':}. 4 
Test (. 1 , y = 2, z = 3 , w = 4)

** kwargs parameter indicates that this is a variable name, it is essentially a dictionary.

When calling test (1, y = 2, z = 3, w = 4), the first parameter passed to a x, a dictionary composed of the remaining parameters passed kwargs, kwargs a dictionary { 'y': 2, 'z': 3, 'w': 4}.

Both models can also be used together, provided that the parameters of an asterisk in the left two asterisks parameters:

DEF Test (X, * args, ** kwargs):
     Print (X)         # results:. 1 
    Print (args)       # result: (2,. 3,. 4) 
    Print (kwargs)      # result: { 'y': 2, 'Z':}. 3 
Test (1,2,3,4, Y = 2, Z =. 3)

Second, the anonymous function

When we passed into the function, in some cases, you do not need too much defined functions, anonymous functions directly into the more convenient.

1. anonymous function format

Anonymous function in the following format:

the lambda X: X +. 1
 # corresponds 
DEF Calc (X)
     return X +. 1

2. anonymous call function

Anonymous functions can not be called directly, must be given a variable:

the lambda X: X +. 1 
FUNC = the lambda X: X +. 1  
 Print (FUNC (10))      # results: 11

 

Guess you like

Origin www.cnblogs.com/lzc69/p/11097998.html