Why use **kwargs in python? What are some real world advantages over using named arguments?

后端 未结 8 1692
小鲜肉
小鲜肉 2020-12-02 09:52

I come from a background in static languages. Can someone explain (ideally through example) the real world advantages of using **kwargs over named arguments

8条回答
  •  天涯浪人
    2020-12-02 10:15

    Here's an example, I used in CGI Python. I created a class that took **kwargs to the __init__ function. That allowed me to emulate the DOM on the server-side with classes:

    document = Document()
    document.add_stylesheet('style.css')
    document.append(Div(H1('Imagist\'s Page Title'), id = 'header'))
    document.append(Div(id='body'))
    

    The only problem is that you can't do the following, because class is a Python keyword.

    Div(class = 'foo')
    

    The solution is to access the underlying dictionary.

    Div(**{'class':'foo'})
    

    I'm not saying that this is a "correct" usage of the feature. What I'm saying is that there are all kinds of unforseen ways in which features like this can be used.

提交回复
热议问题