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

后端 未结 8 1632
小鲜肉
小鲜肉 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:18

    **kwargs are good if you don't know in advance the name of the parameters. For example the dict constructor uses them to initialize the keys of the new dictionary.

    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    
    In [3]: dict(one=1, two=2)
    Out[3]: {'one': 1, 'two': 2}
    
    0 讨论(0)
  • 2020-12-02 10:25

    Another reason you might want to use **kwargs (and *args) is if you're extending an existing method in a subclass. You want to pass all the existing arguments onto the superclass's method, but want to ensure that your class keeps working even if the signature changes in a future version:

    class MySubclass(Superclass):
        def __init__(self, *args, **kwargs):
            self.myvalue = kwargs.pop('myvalue', None)
            super(MySubclass, self).__init__(*args, **kwargs)
    
    0 讨论(0)
提交回复
热议问题