在python函数定义中,*有什么用途?
当我在python3.5.1中浏览glob的代码时,这里定义了函数,为什么函数参数列表中有一个*。如果我将三个参数传递给这个函数,TypeError会引发什么样的结果*?首先感谢。在python 3中,您可以指定在python函数定义中,*有什么用途?,python,Python,当我在python3.5.1中浏览glob的代码时,这里定义了函数,为什么函数参数列表中有一个*。如果我将三个参数传递给这个函数,TypeError会引发什么样的结果*?首先感谢。在python 3中,您可以指定*仅强制参数作为仅关键字参数: def iglob(pathname, *, recursive=False): """Return an iterator which yields the paths matching a pathname pattern. The pattern
*
仅强制参数作为仅关键字参数:
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
def fn(arg1,arg2,*,kwarg1,kwarg2):
... 打印(arg1、arg2、kwarg1、kwarg2)
...
>>>fn(1,2,3,4)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:fn()接受2个位置参数,但给出了4个
>>>fn(1,2,kwarg1=3,kwarg2=4)
1 2 3 4
>>>
在本例中,它强制kwarg1和kwarg2仅作为关键字参数发送。thx,我尝试定义如下函数:def test(name,*),SyntaxError raised:SyntaxError:named参数必须跟在bare*后面。def测试(名称,*,a=None)是正确的方法。再次感谢。
>>>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
>>>