Dynamic parameters for Python:
1, the parameter before a "*": in the function will be transferred to a tuple of parameters.
Func (* func (123,1,2,) result: (123, 1, 2, ' a ')
2, "**args" parameter: The function is turned into a dictionary.
If this is the case, there will be an error because no key or value:def func (**args) is specified: print (args) func (123,1,2, ' a ') result:TypeError:func () takes 0 Positional arguments but 4 were givendef func (**args): print (args) func (a=1,b=2) result:{' a ': 1, ' b ': 2}
3, the situation of mixed dynamic parameters:
def func (*args,**kwargs): print ("%s----%s"% (args,kwargs)) func (1,2,a=1,b=2) Result: (1, 2)----{' b ': 2, ' A ': 1} it's no problem, you need Note that the *args must be in the front **kwargs, and the parameters are the Same.
4, variables when dynamic parameters are in the Case:
In this case, if we directly upload a list to the front, a dict to the Back: def func (*args,**kwargs): print ("%s----%s"% (args,kwargs)) list=[1,2]dic={' a ': 1, ' b ': 2}func (list,dic) Result: ([1, 2], {' b ': 2, ' A ': 1})----the dictionary after {} is empty--! so, we need to call the function to know that the variable is the parameter of *args, which is the parameter of the **args, the correct argument is written: func (*list,**dicresult: (1, 2)----{' a ': 1, ' b ': 2}
This article from "Lu Yaliang" blog, reproduced please contact the author!
Python function Dynamic parameter detailed