【问题标题】:what is the use of * in python function definition? [duplicate]python函数定义中的*有什么用? [复制]
【发布时间】:2016-07-27 19:06:39
【问题描述】:
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


    【解决方案1】:

    在 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 仅作为关键字参数发送。

    【讨论】:

    • thx,我试图定义这样的函数:def test(name, *), SyntaxError raise: SyntaxError: named arguments must follow bare *. def test(name, *, a = None) 是正确的方法。再次感谢。
    猜你喜欢
    • 2022-11-22
    • 2014-02-12
    • 1970-01-01
    • 2011-10-11
    • 2014-07-13
    • 2022-08-15
    • 2021-02-04
    • 2013-05-11
    • 2021-10-18
    相关资源
    最近更新 更多