What is the purpose and use of **kwargs?

前端 未结 13 2192
伪装坚强ぢ
伪装坚强ぢ 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:43

    kwargs is just a dictionary that is added to the parameters.

    A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.

    The what for is not so simple.

    For example (very hypothetical) you have an interface that just calls other routines to do the job:

    def myDo(what, where, why):
       if what == 'swim':
          doSwim(where, why)
       elif what == 'walk':
          doWalk(where, why)
       ...
    

    Now you get a new method "drive":

    elif what == 'drive':
       doDrive(where, why, vehicle)
    

    But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.

    Here you can throw kwargs into play -- you just add kwargs to the signature:

    def myDo(what, where, why, **kwargs):
       if what == 'drive':
          doDrive(where, why, **kwargs)
       elif what == 'swim':
          doSwim(where, why, **kwargs)
    

    This way you don't need to change the signature of your interface function every time some of your called routines might change.

    This is just one nice example you could find kwargs helpful.

提交回复
热议问题