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

后端 未结 4 1550
情深已故
情深已故 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条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 14:54

    Clear and concise:

    In Python 3.5 or greater:

    def foo(a, b=3, *args, **kwargs):
      defaultKwargs = { 'c': 10, 'd': 12 }
      kwargs = { **defaultKwargs, **kwargs }
      
      print(a, b, args, kwargs)
      
      # Do something else
    
    foo(1) # 1 3 () {'c': 10, 'd': 12}
    foo(1, d=5) # 1 3 () {'c': 10, 'd': 5}
    foo(1, 2, 4, d=5) # 1 2 (4,) {'c': 10, 'd': 5}
    

    Note: you can use In Python 2

    kwargs = merge_two_dicts(defaultKwargs, kwargs)
    

    In Python 3.5

    kwargs = { **defaultKwargs, **kwargs }
    

    In Python 3.9

    kwargs = defaultKwargs | kwargs  # NOTE: 3.9+ ONLY
    

提交回复
热议问题