First, several types of points need to clear function parameters:
- (No need to write the name of the parameter in the call, the location parameters written directly numerical order );
- The default parameters: function call type parameter can write from time to write, because of the default, but if you change the default value, must bring variable name calling ;
- Variable parameters: Definition Format: * varibale, can pass any number of parameters, very valuable details, please refer to: Liao Xuefeng Python Tutorial ;
- Keyword arguments: Definition Format: ** kwarg, refer to the link above;
Second, we must find out the order of combination of these parameters:
Defined function in Python, can be a mandatory parameter, default parameter, the variable parameter, keywords and named keyword parameters, these five parameters can be used in combination. Note, however, the order of the parameters must be defined: mandatory parameters, default parameters, variable parameter, named keyword arguments and keyword arguments.
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)
When the function call, Python interpreter position automatically according to the parameters and the corresponding parameter name parameter passed into it.
>>> 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', '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 = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
The most amazing is through a tuple and dict, you can also call the above function:
>>> 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': '#'}
Therefore, for any function, it is available through a similar func(*args, **kw)
call its forms, regardless of its parameters are defined.
Above Complete Reference: Liao Xuefeng official website --Python tutorial - Function parameters!