Calling a Python function with *args,**kwargs and optional / default arguments

后端 未结 4 1546
情深已故
情深已故 2020-11-27 14:06

In python, I can define a function as follows:

def func(kw1=None,kw2=None,**kwargs):
   ...

In this case, i can call func as:



        
4条回答
  •  -上瘾入骨i
    2020-11-27 14:51

    If you want to do a mixture of both remember that *args and **kwargs must be the last parameters specified.

    def func(arg1,arg2,*args,kw1=None,kw2=None,**kwargs): #Invalid
    def func(arg1,arg2,kw1=None,kw2=None,*args,**kwargs): #Valid
    

    The comments seem to be based on mixing up how a function definition is constructed compared to how the arguments provided are assigned back to the parameters specified in the definition.

    This is the definition of this function which has 6 parameters. It is called by passing named and unnamed arguments to it in a function call.

    For this example... When an argument is named when calling the function it can be provided out of order. arg1 and arg2 are mandatory parameters and if not passed to the function as named arguments, then they must be assigned in order from the provided unnamed arguments. kw1 and kw2 have default values provided in the function definition so they are not mandatory, but if not provided for as named arguments they will take any available values from the remaining provided unnamed arguments. Any unnamed arguments left over are provided to the function in an array called args Any named arguments that do not have a corresponding parameter name in the function definition are provided to the function call in a dictionary called kwargs.

提交回复
热议问题