python - python函数定义中*有什么用?

标签 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

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

最佳答案

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

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

关于python - python函数定义中*有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467057/

相关文章:

python - matplotlib 图的插图缩放标记在错误的角上

python - 当需要高精度时,Matplotlib 无法正确绘图

python 声音("Bell")

python - Swig C++ python 包装器文件解释?

python - 如何与后台 Python 实例通信?

python - Pandas 数据框计数行值

python - 将 Google 电子表格数据转换为 pandas 数据框

python - 用 Homebrew 软件安装python后如何更改pip3路径?

python - 在 GAE 上使用 boto3 - Popen 出现问题

python - json.decoder.JSONDecodeError : Expecting value: line 1 column 1 (char 0) KeyError: ["Data Bytes 1: "]