python mandatory parameters, default parameters, variable parameters and keyword parameters

Transfer: https://www.liaoxuefeng.com/wiki/897692888725344/897693568201440

variable parameter

In Python functions you may also define variable parameters. As the name suggests, the variable parameter is the number of arguments passed is variable, and may be one, two to any number, and may be 0.

We mathematical entitled example, given a set of numbers a, b, c ......, Calculate a2 + b2 + c2 + .......

To define this function, we must determine the parameters entered. Since the number of parameter uncertainty, we can first think of a, b, c ...... tuple as a list or passed in so that the function can be defined as follows:

def calc(numbers):
    sum = 0 for n in numbers: sum = sum + n * n return sum 

But when you call, you need to assemble a list or tuple:

>>> calc([1, 2, 3])
14 >>> calc((1, 3, 5, 7)) 84 

If using a variable parameter, the function call can be simplified manner in such a way:

>>> calc(1, 2, 3)
14 >>> calc(1, 3, 5, 7) 84 

So, we put parameter to the function of the variable parameters:

def calc(*numbers):
    sum = 0 for n in numbers: sum = sum + n * n return sum 

Defined and variable parameters list or tuple define parameters compared, only the front of the parameter plus a *number. Inside the function, the parameter numbersreceived is a tuple, and therefore, the function code is completely intact. However, when you call the function, you can pass any number of parameters, including 0 parameters:

>>> calc(1, 2)
5
>>> calc() 0 

If you already have a list or tuple, to be called a variable parameter how to do? We can do this:

>>> nums = [1, 2, 3]
>>> calc(nums[0], nums[1], nums[2]) 14 

Of course, such an approach is feasible, the problem is too complicated, so Python allows you to add a list or in front of the tuple *number of elements in the list or tuple become variable parameters pass in:

>>> nums = [1, 2, 3]
>>> calc(*nums) 14 

The wording is quite useful and very common.

Keyword arguments

Variable parameters allow you pass 0 or any number of parameters, these variable parameters are automatically assembled into a tuple in the function call. The key parameter allows you pass 0 or any number of parameters including the parameter name, the parameters of these keywords automatically assembled into a dict inside the function. Below is an example:

def person(name, age, **kw):
    print 'name:', name, 'age:', age, 'other:', kw 

Function personin addition to a mandatory parameter nameand age, also accepts keyword arguments kw. When calling this function, you can only pass mandatory parameters:

>>> person('Michael', 30)
name: Michael age: 30 other: {}

You can also pass an arbitrary number of keyword arguments:

>>> 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 arguments What is the use? It can extend the functionality of the function. For example, in persona function, we can guarantee received nameand agethese two parameters, however, if the caller is willing to provide additional parameters, we can receive. Imagine you're making a user registration function, in addition to user name and age are required, other options are available, use keyword parameters to define the function will be able to meet the registration requirements.

The variable parameters and the like, may be first assembled a dict, then, to pass in the dict converts keywords parameters:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, city=kw['city'], job=kw['job']) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'} 

Of course, the complex can call the above simplified wording:

>>> kw = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, **kw) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'} 

Parameter combination

In-defined functions Python, you can use mandatory parameters, default parameters, variable parameters and keyword parameters, these four parameters can be used together, or only some, but please note that the order of the parameters must be defined: Required parameters, default parameters, variable parameters and keyword parameters.

Such as the definition of a function, including the above four kinds of parameters:

def func(a, b, c=0, *args, **kw): print 'a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw 

When the function call, Python interpreter position automatically according to the parameters and the corresponding parameter name parameter passed into it.

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

The most amazing is through a tuple and dict, you can also call the function:

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

Therefore, for any function, it is available through a similar func(*args, **kw)call its forms, regardless of its parameters are defined.

summary

Python functions have very flexible parametric form, either simple call, and can pass very complex parameters.

The default parameter must use immutable objects, if the object is a variable, run there will be a logical error!

To note defines the syntax of variable parameters and keyword parameters:

*argsIt is a variable parameter, args a tuple is received;

**kwKeyword parameters, kw received a dict.

And how to pass variable parameters and keyword arguments when calling function syntax:

Variable parameters can be passed directly: func(1, 2, 3), but also to the assembly list or tuple, and through *argsIncoming: func(*(1, 2, 3));

Keyword parameters can be passed directly: func(a=1, b=2), but also to assemble dict, and then through the **kwpass: func(**{'a': 1, 'b': 2}).

Use *argsand **kwis the habit of writing Python, of course, you can also use other parameter name, but the best use of idioms.

Guess you like

Origin www.cnblogs.com/apple2016/p/10959727.html