## python

## Python function parameters

Regarding the parameters of Python, the most commonly seen in various codes is def func(*args, **kw)this parameter combination. This article discusses how we can get such a parameter combination step by step.

Overview

Python's function definition is very simple, but its flexibility is very large. In addition to the normally defined mandatory parameters, you can also use default parameters, variable parameters, and keyword parameters, so that the interface defined by the function can not only handle complex parameters, but also simplify the code of the caller.

Positional parameter

Positional parameters are our most common function parameters, for example, the following pow function to complete the power operation :

def pow (x, n) :

s = 1 while n> 0 : n = n- 1 s = s * x returns

pow(x, n)The function has two parameters: xand n, both of which are positional parameters. When the function is called, the two values passed in are assigned to the parameter x and in order according to the position order n.

Default parameter

Since we often calculate x^2, we can set n the default value of the second parameter to 2:

def pow (x, n = 2 ) :

s = 1 while n> 0 : n = n- 1 s = s * x returns

In this way, when we call pow(5), it is equivalent to calling pow(5, 2):

>>> power ( 5 )

25

>>> power ( 5 , 2 )

25

When setting the default parameters, there are a few points to note:

The required parameters are in the front, and the default parameters are in the back, otherwise the Python compiler will report an error;

When the function has multiple parameters, put the parameters with large changes in the front and the parameters with small changes in the back. Parameters with small changes can be used as default parameters.

It is also possible to provide some default parameters out of order. When some default parameters are not provided in order, the parameter name needs to be written.

The default parameter has the largest pit, as follows:

>>> def add_end (L = []) :

... L.append ( 'END' )

... return L

...

>>> add_end ()

[ 'END' ]

>>> add_end ()

[ ' END ' , ' END ' ]

>>> add_end ()

[ ' END ' , ' END ' , ' END ' ]

We found that every time a add_end()function is called with default parameters , it will "remember" the result of the previous call.

The reasons are as follows:

When the Python function is defined, L the value of the default parameter is calculated, that is [], because the default parameter L is also a variable, it points to the object [], each time the function is called, if L the content is changed , the default parameter is called the next time The content has changed, no longer when the function is defined [].

Therefore, the default parameters must point to immutable objects! ! !

The above example is modified as follows:

def add_end (L = None) :

if L == None:

L = []

L.append ( 'END' ) return L

### variable parameter

Taking a math problem as an example, given a set of numbers a, b, c ..., please calculate a ^ 2 + b ^ 2 + c ^ 2 + ..., because the parameters are uncertain, first think of a, b, c ... as one list or tuple pass in.

def calc (numbers) :

sum = 0 for n in numbers: sum = sum + n * n return sum

When passing parameters, you need to assemble one tuple or list:

>>> calc ([ 1 , 2 , 3 ])

14

>>> calc (( 1 , 3 , 5 , 7 ))

84

If using variable parameters:

def calc (* numbers) :

sum = 0 for n in numbers: sum = sum + n * n return sum

Inside the function, the parameter numbers received is a tuple, so the function code is completely unchanged. However, when calling this function, you can pass in any number of parameters, including 0 parameters:

>>> calc ( 1 , 2 )

5

>>> calc ()

0

If there is already an list OR tuple, you can use *it to unpack it when passing parameters :

>>> nums = [ 1 , 2 , 3 ]

>>> calc (* nums)

14

*nums Indicates that nums all elements of this list are passed in as variable parameters.

Keyword parameters

Keyword parameters allow you to pass in 0 or any number of parameters with parameter names. These keyword parameters are automatically assembled into a dict inside the function. E.g:

def person (name, age, ** kw) :

print ( 'name:' , name, 'age:' , age, 'other:' , kw)

When calling this function, you can only pass in the required parameters:

>>> person ( 'Colin' , 24 )

name: Colin age: 24 other: {}

You can also pass in any number of keyword parameters:

>>> person ( 'Bob' , 35 , city = 'Beijing' )

name: Bob age: 35 other: { 'city' : 'Beijing' }

>>> person ( 'Adam' , 45 , gender = 'M' , job = 'Engineer' )

name: Adam age: 45 other: { 'gender' : 'M' , 'job' : 'Engineer' }

Keyword parameters can extend the function of functions, for example: a user registration function is being done, except that the user name and age are required, other options are all available. Using keyword parameters to define this function can meet the needs of registration.

Similar to variable parameters, one can be assembled first dict, and then dictconverted into keyword parameters:

>>> extra = { 'city' : 'Beijing' , 'job' : 'Engineer' }

>>> person ( 'Jack' , 24 , city = extra [ 'city' ], job = extra [ 'job' ] )

name: Jack age: 24 other: { 'city' : 'Beijing' , 'job' : 'Engineer' }

Can be simplified to:

>>> extra = { 'city' : 'Beijing' , 'job' : 'Engineer' }

>>> person ( 'Jack' , 24 , ** extra)

**extraIt means that extra all key-values of this dict are passed into the function **kw parameters with keyword parameters , and kwa dict will be obtained. Note that the kw obtained dict is extra a copy, and kw the changes will not affect the outside of the function extra.

Command keyword parameters

For keyword arguments, the caller of the function can pass in any unrestricted keyword arguments. If you want to limit the name of keyword parameters, you can use named keyword parameters. For example, only accept city and job as keyword parameters:

def person (name, age, *, city, job) :

print (name, age, city, job)

**kw Unlike keyword parameters , named keyword parameters require a special separator, *and *subsequent parameters are considered named keyword parameters.

The calling method is as follows:

>>> person ( 'Jack' , 24 , city = 'Beijing' , job = 'Engineer' )

Jack 24 Beijing Engineer

If there is already a variable parameter in the parameter, the following command keyword parameter does not need a separator *:

def person (name, age, * args, city, job) :

print (name, age, args, city, job)

Named keyword parameters must be passed in parameter names, which is different from positional parameters.

Parameter combination

The order of parameter definition must be: mandatory parameters, default parameters, variable parameters, named keyword parameters and keyword parameters. E.g:

>>> def f1 (a, b, c = 0 , * args, ** kw) :

... print ( 'a =' , a, 'b =' , b, 'c =' , c, 'args = ' , args, ' kw = ' , kw)

...

>>> def f2 (a, b, c = 0 , *, d, ** kw) :

... print ( ' a = ' , a, 'b =' , b, 'c =' , c, 'd =' , d, 'kw =' , kw)

The function call is as follows:

>>> f1 ( 1 , 2 )

a = 1 b = 2 c = 0 args = () kw = ()

>>> f1 ( 1 , 2 , c = 3 )

a = 1 b = 2 c = 3 args = () kw = {}

>>> f1 ( 1 , 2 , 3 )

a = 1 b = 2 c = 3 args = () kw = {}

>>> f1 ( 1 , 2 , 3 , 'a' ,'b' )

a = 1 b = 2 c = 3 args = ( 'a' , 'b' ) kw = {}

>>> f1 ( 1 , 2 , 3 , 'a' , 'b' , x = 99 )

a = 1 b = 2 c = 3 args = ( 'a' , 'b' ) kw = { 'x' : 99 }

>>> f2 ( 1 , 2 , d = 99 ,ext = None )

a = 1b = 2 c = 0 d = 99 kw = { 'ext' : None }

A may also be used tupleand dictcalls for these functions:

>>> args = ( 1 , 2 , 3 , 4 )

>>> kw = { 'd' : 99 , 'x' : '#' }

>>> f1 (* args, ** kw)

a = 1 b = 2 c = 3 args = ( 4 ,) kw = { 'd' : 99 , 'x' : '#' }

>>> args = ( 1 , 2 , 3 )

>>> kw = { 'd' :88 ,'x' : '#' }

>>> f2 (* args, ** kw)

a = 1 b = 2 c = 3 d = 88 kw = { 'x' : '#' }

# to sum up

- *args Is a variable parameter, args receive one tuple;
- **kw Is a keyword parameter, kw receive one dict;
- Either directly into the variable parameter: func(1, 2, 3)it can also be assembled into one list or tuple afferent: func(*(1, 2, 3));
- Keyword parameters can be passed directly: func(a=1, b=2)can also be assembled into a dict Incoming: func(**{'a': 1, 'b': 2});
- Named keyword parameters are to limit the parameter names that the caller can pass in, while providing default values;