What is the purpose and use of **kwargs?

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

    Here is an example that I hope is helpful:

    #! /usr/bin/env python
    #
    def g( **kwargs) :
      print ( "In g ready to print kwargs" )
      print kwargs
      print ( "in g, calling f")
      f ( **kwargs )
      print ( "In g, after returning from f")
    
    def f( **kwargs ) :
      print ( "in f, printing kwargs")
      print ( kwargs )
      print ( "In f, after printing kwargs")
    
    
    g( a="red", b=5, c="Nassau")
    
    g( q="purple", w="W", c="Charlie", d=[4, 3, 6] )
    

    When you run the program, you get:

    $ python kwargs_demo.py 
    In g ready to print kwargs
    {'a': 'red', 'c': 'Nassau', 'b': 5}
    in g, calling f
    in f, printing kwargs
    {'a': 'red', 'c': 'Nassau', 'b': 5}
    In f, after printing kwargs
    In g, after returning from f
    In g ready to print kwargs
    {'q': 'purple', 'c': 'Charlie', 'd': [4, 3, 6], 'w': 'W'}
    in g, calling f
    in f, printing kwargs
    {'q': 'purple', 'c': 'Charlie', 'd': [4, 3, 6], 'w': 'W'}
    In f, after printing kwargs
    In g, after returning from f
    

    The key take away here is that the variable number of named arguments in the call translate into a dictionary in the function.

提交回复
热议问题