Python 中的许多内置函数和标准库函数的函数签名都以\结尾
示例
>>> help(divmod)
Help on built-in function divmod in module builtins:
divmod(x, y, /)
Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
def my_func(arg, /):
pass
print(repr(inspect.signature(my_func)))
# Output: <Signature (arg, /)>
这里的/意味着什么以及为什么使用它?
最佳答案
/
是在 python 3.8 中添加的,意味着它前面的所有参数都只是位置参数,不能在 kwargs 方法中提供,如本文档所示:https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters
There is a new function parameter syntax / to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments. This is the same notation shown by help() for C functions annotated with Larry Hastings’ Argument Clinic tool.
In the following example, parameters a and b are positional-only, while c or d can be positional or keyword, and e or f are required to be keywords:
def f(a, b, /, c, d, *, e, f): print(a, b, c, d, e, f)
The following is a valid call:
f(10, 20, 30, d=40, e=50, f=60)
However, these are invalid calls:
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument
关于python - python函数的签名是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68233164/