Home  >  Article  >  Backend Development  >  Detailed explanation of python function asterisk parameter

Detailed explanation of python function asterisk parameter

高洛峰
高洛峰Original
2016-10-20 09:50:042090browse

In the definition of the function, by adding an asterisk before the parameter, the multiple parameters passed in are converted into an object, tuple or dictionary, which can be said to collect these parameter values.

Add an asterisk before the parameter to indicate that all values ​​are placed in the same tuple, and the return value of this parameter is a tuple.

Add two asterisks before the parameter to indicate that all values ​​are placed in the same dictionary. The return value of this parameter is a dictionary.

>>> def print_param(x, y, z = 3, *pospar, **keypar):
    print x,y,z
    print pospar
    print keypar
   
>>> print_param(3,4,5,6,7,8,m = 1,n = 2)
3 4 5
(6, 7, 8)
{'m': 1, 'n': 2}

Assign parameters

In the call of the function, by adding an asterisk before the parameter, the passed parameter must be a tuple or dictionary, and its value can be converted into the value of the corresponding variable. This process can be seen as Assignment of parameter values.

Add an asterisk before the parameter to indicate that the tuple value is assigned to the corresponding function parameter value.

Add two asterisks before the parameter to indicate that the value in the dictionary is assigned to the key. The key should be used as the parameter name in the function definition.

>>> def add(x,y):
    print x,y
    return x + y
   
>>> add(*param)
1 2
3
   
>>> def test(name,age):
    print name,age
   
>>> m = {'name':'xiaoli','age':'12'}
>>> test(**m)
xiaoli 12
>>> m = {'name':'xiaoli','age':12}
>>> test(**m)
xiaoli 12



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn