Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python函数定义中,*有什么用途?_Python - Fatal编程技术网

在python函数定义中,*有什么用途?

在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

当我在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 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
>>>