星号(*)作为python函数的自变量[重复]
问题内容:
这个问题已经在这里有了答案 :
仅关键字参数 (1个答案)
os.removexattr的Python文档-“
*”(星号)参数是什么意思?
(1个答案)
1年前关闭。
我在看glob
函数的定义时,发现第二个参数很简单*
。
def glob(pathname, *, recursive=False):
"""Return a list of paths matching a pathname pattern.
[...]
"""
return list(iglob(pathname, recursive=recursive))
有什么意义*
呢?
问题答案:
该*
指示的位置参数的结尾。此后的每个参数只能由关键字指定。这在PEP
3102中
定义
>>> def foo1(a, b=None):
... print(a, b)
...
>>> def foo2(a, *, b=None):
... print(a, b)
...
>>> foo1(1, 2)
1 2
>>> foo2(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo1() takes 1 positional argument but 2 were given
>>> foo2(1, b=2)
1 2