Bare asterisk in function arguments?

后端 未结 6 1188
孤街浪徒
孤街浪徒 2020-11-22 06:22

What does a bare asterisk in the arguments of a function do?

When I looked at the pickle module, I see this:

pickle.dump(obj, file, protocol=None, *,         


        
6条回答
  •  旧巷少年郎
    2020-11-22 07:21

    I've found the following link to be very helpful explaining *, *args and **kwargs:

    https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/

    Essentially, in addition to the answers above, I've learned from the site above (credit: https://pythontips.com/author/yasoob008/) the following:

    With the demonstration function defined first below, there are two examples, one with *args and one with **kwargs

    def test_args_kwargs(arg1, arg2, arg3):
        print "arg1:", arg1
        print "arg2:", arg2
        print "arg3:", arg3
    
    # first with *args
    >>> args = ("two", 3,5)
    >>> test_args_kwargs(*args)
    arg1: two
    arg2: 3
    arg3: 5
    
    # now with **kwargs:
    >>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
    >>> test_args_kwargs(**kwargs)
    arg1: 5
    arg2: two
    arg3: 3
    

    So *args allows you to dynamically build a list of arguments that will be taken in the order in which they are fed, whereas **kwargs can enable the passing of NAMED arguments, and can be processed by NAME accordingly (irrespective of the order in which they are fed).

    The site continues, noting that the correct ordering of arguments should be:

    some_func(fargs,*args,**kwargs)
    

提交回复
热议问题