What is the purpose and use of **kwargs?

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

    You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):

    >>> def print_keyword_args(**kwargs):
    ...     # kwargs is a dict of the keyword args passed to the function
    ...     for key, value in kwargs.iteritems():
    ...         print "%s = %s" % (key, value)
    ... 
    >>> print_keyword_args(first_name="John", last_name="Doe")
    first_name = John
    last_name = Doe
    

    You can also use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:

    >>> kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
    >>> print_keyword_args(**kwargs)
    first_name = Bobby
    last_name = Smith
    

    The Python Tutorial contains a good explanation of how it works, along with some nice examples.

    <--Update-->

    For people using Python 3, instead of iteritems(), use items()

提交回复
热议问题