python: dynamic parameters * args

Dynamic parameters

  As the name suggests, is the number of parameters passed in the dynamic parameter is dynamic, and may be one, two to any number, and may be 0. When not needed, you can ignore the dynamic function, do not pass any value to it.

There are two dynamic parameters Python, respectively *args, and **kwargsthe key there is the difference between one and two asterisks instead argsand kwargsthe difference in names, you can actually use *anyor **whatevermanner. But just as self as default we all use *argsand**kwargs .

Note: The dynamic parameters, must be placed behind all the positional parameters and default parameters!

def func(name, age, sex='male', *args, **kwargs):
    pass

*args

One asterisk denotes receives any arguments. When called, the actual parameters will be packaged into a tuple incoming form parameters. If the argument is a list, the entire list will be passed as a parameter. E.g:

 

DEF FUNC (* args):
     "" " 
    * denotes the number of receiving any number of parameters, the actual parameter will be called when packaged as a tuple incoming arguments 
    : param args: 
    : return: 
    " "" 
    Print args 

    for I in args :
         Print I 


FUNC ({ ' name ' : ' Kobe ' }, 123, ' Hello ' , [ ' A ' , ' B ' , ' C ' ])

 

operation result:

({'name': 'kobe'}, 123, 'hello', ['a', 'b', 'c'])
{'name': 'kobe'}
123
hello
['a', 'b', 'c']

We can see, the first print args parameter is a tuple, then were printed for each parameter passed.

Sometimes we pass a list of purported want all elements in the list are passed as parameters into account, here directly [ 'a', 'b', 'c'] seen as a whole, how do?

In fact, only when preceded by a call number * , you will be able to achieve the transfer list each element into it.

In fact, not only the list, the sequence of any type of data object, such as a string, a tuple can be the internal element in this way one by one passed as a parameter to the function. The dictionary, it will be passed in all the key one by one.

DEF FUNC (* args):
     "" " 
    * denotes the number of receiving any number of parameters, the actual parameter will be called when packaged as a tuple incoming arguments 
    : param args: 
    : return: 
    " "" 
    for I in args:
         Print I 


FUNC ( * [ ' A ' , ' B ' , ' C ' ])

Output:

a
b
c

In particular, there can be only one parameter to add an asterisk before you call, and must be placed at the end face

DEF FUNC (* args):
     "" " 
    * denotes the number of receiving any number of parameters, the actual parameter will be called when packaged as a tuple incoming arguments 
    : param args: 
    : return: 
    " "" 
    for I in args:
         Print I 


FUNC ( 123, ' Hello ' , [ ' A ' , ' B ' , ' C ' ], * { ' name ' : ' Kobe ' , ' Age ' : 41 is})

Output: The dictionary key value as an argument the

123
hello
['a', 'b', 'c']
age
name

 

Guess you like

Origin www.cnblogs.com/gcgc/p/11426478.html