* 在python函数定义中的用途是什么?

inm*_*awn 4 python

def iglob(pathname, *, recursive=False):
"""Return an iterator which yields the paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.

If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
it = _iglob(pathname, recursive)
if recursive and _isrecursive(pathname):
    s = next(it)  # skip empty string
    assert not s
return it
Run Code Online (Sandbox Code Playgroud)

当我在python3.5.1中浏览glob的代码时,这里定义的函数,为什么函数参数列表中有一个*。如果我将三个参数传递给 TypeError 引发的这个函数,* 的效果是什么?先谢谢了。

rit*_*t93 6

在 python 3 中,您可以*在此之后勉强指定强制参数作为仅关键字参数:

>>>def fn(arg1, arg2, *, kwarg1, kwarg2):
...     print(arg1, arg2, kwarg1, kwarg2)
... 
>>> fn(1, 2, 3, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fn() takes 2 positional arguments but 4 were given
>>> fn(1, 2, kwarg1=3, kwarg2=4)
1 2 3 4
>>> 
Run Code Online (Sandbox Code Playgroud)

在此示例中,它强制 kwarg1 和 kwarg2 仅作为关键字参数发送。