This article is not original, excerpted from: http://www.cnblogs.com/paulwinflo/p/5764748.htmlVariable parameters
In the Python function, you can also define mutable parameters. As the name implies, the variable parameter is the number of parameters passed in is variable, can be one, 2 to any, or 0.
We take the math titled example, given a set of numbers a,b,c ..., please calculate a2 + b2 + C2 + ....
To define this function, we must determine the input parameters. As the number of arguments is uncertain, we first think that we can put a,b,c ... Passed in as a list or tuple, 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 called, a list or tuple needs to be assembled first:
>>> calc([1, 2, 3])14>>> calc((1, 3, 5, 7))84
If you take advantage of mutable parameters, the way you call a function can be simplified to this:
>>> calc(1, 2, 3)14>>> calc(1, 3, 5, 7)84
So, let's change the parameter of the function to a variable parameter:
def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum
When you define a mutable parameter and define a list or tuple parameter, just precede the parameter with a *
number. Inside the function, the parameter numbers
receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters:
>>> calc(1, 2)5>>> calc()0
What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:
>>> nums = [1, 2, 3]>>> calc(nums[0], nums[1], nums[2])14
This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to add a number in front of a list or a tuple *
, the elements of a list or a tuple into a mutable parameter to pass in:
>>> nums = [1, 2, 3]>>> calc(*nums)14
This writing is quite useful and common.
Keyword parameters
Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict. Take a look at the example:
def person(name, age, **kw): print ‘name:‘, name, ‘age:‘, age, ‘other:‘, kw
person
name
age
The function accepts the keyword parameter in addition to the required parameters kw
. When you call this function, you can pass in only the required parameters:
>>> person(‘Michael‘, 30)name: Michael age: 30 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‘}
What is the keyword argument for? It can extend the functionality of the function. For example, in a person
function, we are guaranteed to receive name
and both age
parameters, but if the caller is willing to provide more arguments, we can receive them. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.
Similar to variable parameters, you can also assemble a dict, and then convert the dict into a keyword parameter:
>>> 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 above complex invocation can be simplified:
>>> kw = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}>>> person(‘Jack‘, 24, **kw)name: Jack age: 24 other: {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}
Parameter combinations
Defining functions in Python can be done with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of the parameters definition must be: required, default, variable, and keyword parameters. 4
For example, define a function that contains the above 4 parameters:
def func(a, b, c=0, *args, **kw): print ‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw
At the time of the function call, the Python interpreter automatically passes the corresponding parameters according to the parameter location and argument name.
>>> 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, ' B ', x= 99) A = 1 B = 2 c = 3 args = ( ' a ', ' B ') kw = {99}
The most amazing thing is that 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}
So, for any function, it can be called in a similar func(*args, **kw)
way, regardless of how its arguments are defined.
Summary
Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.
The default parameter must be used immutable object, if it is a mutable object, run there will be a logic error!
Be aware of the syntax for defining mutable parameters and keyword parameters:
*args
is a variable parameter, and args receives a tuple;
**kw
is a keyword parameter, kw receives a dict.
And how to pass in the syntax for variable and keyword arguments when calling a function:
Variable parameters can be directly passed func(1, 2, 3)
in:, you can first assemble a list or a tuple, and then pass in *args
: func(*(1, 2, 3))
;
Keyword parameters can be directly passed in: func(a=1, b=2)
, you can first assemble dict, and then pass in **kw
: func(**{‘a‘: 1, ‘b‘: 2})
.
It *args
is customary to use and **kw
be python, but it is also possible to use other parameter names, but it's best to get used to idioms.
python* and * * parameter issues