正斜杠“/"是什么意思?在 Python 方法签名中,如 help(foo) 所示? [英] What is the meaning of a forward slash "/" in a Python method signature, as shown by help(foo)?
问题描述
在help(foo)
交互返回的签名中,一个/
是什么意思?
In the signature returned interactively by help(foo)
, what is the meaning of a /
?
In [37]: help(object.__eq__)
Help on wrapper_descriptor:
__eq__(self, value, /)
Return self==value.
In [55]: help(object.__init__)
Help on wrapper_descriptor:
__init__(self, /, *args, **kwargs)
Initialize self. See help(type(self)) for accurate signature.
我认为这可能与仅关键字参数有关,但事实并非如此.当我使用仅关键字参数创建自己的函数时,位置参数和仅关键字参数由 *
(如预期)分隔,而不是由 /
分隔./
是什么意思?
I thought it might be related to keyword-only arguments, but it's not. When I create my own function with keyword-only arguments, positional and keyword-only arguments are separated by *
(as expected), not by /
. What does the /
mean?
推荐答案
如此处所述,/"为参数标记仅位置参数的结束(参见 此处),即不能用作关键字参数的参数.在 __eq__(self, value,/)
的情况下,斜线在末尾,这意味着所有参数仅在 __init__
的情况下被标记为位置只有自我,即没有,只是位置.
As explained here, the '/' as an argument marks the end of arguments that are positional only (see here), i.e. arguments you can't use as keyword parameters. In the case of __eq__(self, value, /)
the slash is at the end, which means that all arguments are marked as positional only while in the case of your __init__
only self, i.e. nothing, is positional only.
这以前仅用于内置函数,但 自 Python 3.8 起,你可以在你自己的函数中使用它.\
的自然伴侣是 *
,它允许标记仅关键字参数的开头.使用两者的示例:
This was previously only used for built-in functions but since Python 3.8, you can use this in your own functions. The natural companion of \
is *
which allows to mark the beginning of keyword-only arguments. Example using both:
# a, b are positional-only. e,f keyword-only
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
# valid call
f(10, 20, 30, d=40, e=50, f=60)
# 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 方法签名中,如 help(foo) 所示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!