python - python函数的签名是什么

标签 python function

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/

相关文章:

Python 的 str.replace 不抛出异常

python - 在 Python 中删除 Root 权限

python - python 写入输出 csv 文件

javascript 摘要函数

javascript - 将参数传递给函数

java - 多次调用函数或创建变量

python - 如何使用文本文件创建登录名

python - Pandas 在数据框中的字符串旁边获取值

python - 如何判断最后一个函数是否在类: Python中被调用

c++ - 字母输入运行无限循环