Bare asterisk in function arguments?
函数参数中的星号有什么作用?
当我查看pickle模块时,我看到了:(http://docs.python.org/3.3/library/pickle.html pickle.dump)
1 | pickle.dump(obj, file, protocol=None, *, fix_imports=True) |
我知道在参数前面有一个单星号和两个星号(对于变量个数的参数),但这不在任何前面。我很肯定这和泡菜无关。这可能只是发生这种情况的一个例子。我只在把这个发给口译员时才知道它的名字:
1 2 3 4 5 | >>> def func(*): ... pass ... File"<stdin>", line 1 SyntaxError: named arguments must follow bare * |
如果重要的话,我现在使用的是Python3.3.0。
bare
有关详细信息,请参阅此答案或python 3文档。
当原始答案完全回答问题时,只需添加一些相关信息。单个星号的行为源自
1 2 3 4 5 6 7 | The second syntactical change is to allow the argument name to be omitted for a varargs argument. The meaning of this is to allow for keyword-only arguments for functions that would not otherwise take a varargs argument: def compare(a, b, *, key=None): ... |
在简单的英语中,它意味着要传递key的值,需要显式地将其作为
1 2 3 4 5 6 7 8 9 | def func(*, a, b): print(a) print(b) func("gg") # TypeError: func() takes 0 positional arguments but 1 was given func(a="gg") # TypeError: func() missing 1 required keyword-only argument: 'b' func(a="aa", b="bb", c="cc") # TypeError: func() got an unexpected keyword argument 'c' func(a="aa", b="bb","cc") # SyntaxError: positional argument follows keyword argument func(a="aa", b="bb") # aa, bb |
上面的例子带有**kwargs
1 2 3 4 5 6 | def func(*, a, b, **kwargs): print(a) print(b) print(kwargs) func(a="aa",b="bb", c="cc") # aa, bb, {'c': 'cc'} |
我发现以下链接对解释
https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained-解释/
基本上,除了上面的答案,我还从上面的网站(学分:https://pythontips.com/author/yasoob008/)学到了以下内容:
下面定义的演示函数有两个例子,一个是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 |
因此,
网站继续,注意到正确的参数顺序应该是:
1 | some_func(fargs,*args,**kwargs) |