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

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

    There are two common cases:

    First: You are wrapping another function which takes a number of keyword argument, but you are just going to pass them along:

    def my_wrapper(a, b, **kwargs):
        do_something_first(a, b)
        the_real_function(**kwargs)
    

    Second: You are willing to accept any keyword argument, for example, to set attributes on an object:

    class OpenEndedObject:
        def __init__(self, **kwargs):
            for k, v in kwargs.items():
                setattr(self, k, v)
    
    foo = OpenEndedObject(a=1, foo='bar')
    assert foo.a == 1
    assert foo.foo == 'bar'
    

提交回复
热议问题