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

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

提交回复
热议问题