What is the purpose and use of **kwargs?

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

    Unpacking dictionaries

    ** unpacks dictionaries.

    This

    func(a=1, b=2, c=3)
    

    is the same as

    args = {'a': 1, 'b': 2, 'c':3}
    func(**args)
    

    It's useful if you have to construct parameters:

    args = {'name': person.name}
    if hasattr(person, "address"):
        args["address"] = person.address
    func(**args)  # either expanded to func(name=person.name) or
                  #                    func(name=person.name, address=person.address)
    

    Packing parameters of a function

    def setstyle(**styles):
        for key, value in styles.iteritems():      # styles is a regular dictionary
            setattr(someobject, key, value)
    

    This lets you use the function like this:

    setstyle(color="red", bold=False)
    

提交回复
热议问题