What is the purpose and use of **kwargs?

前端 未结 13 2254
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:59

What are the uses for **kwargs in Python?

I know you can do an objects.filter on a table and pass in a **kwargs argument. &nbs

13条回答
  •  無奈伤痛
    2020-11-21 05:57

    Motif: *args and **kwargs serves as a placeholder for the arguments that need to be passed to a function call

    using *args and **kwargs to call a function

    def args_kwargs_test(arg1, arg2, arg3):
        print "arg1:", arg1
        print "arg2:", arg2
        print "arg3:", arg3
    

    Now we'll use *args to call the above defined function

    #args can either be a "list" or "tuple"
    >>> args = ("two", 3, 5)  
    >>> args_kwargs_test(*args)
    

    result:

    arg1: two
    arg2: 3
    arg3: 5


    Now, using **kwargs to call the same function

    #keyword argument "kwargs" has to be a dictionary
    >>> kwargs = {"arg3":3, "arg2":'two', "arg1":5}
    >>> args_kwargs_test(**kwargs)
    

    result:

    arg1: 5
    arg2: two
    arg3: 3

    Bottomline : *args has no intelligence, it simply interpolates the passed args to the parameters(in left-to-right order) while **kwargs behaves intelligently by placing the appropriate value @ the required place

提交回复
热议问题