如 help(foo) 所示,Python 方法签名中的正斜杠“/”是什么意思?
What is the meaning of a forward slash "/" in a Python method signature, as shown by help(foo)?
help(foo)
交互返回的签名中,一个/
是什么意思?
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.
我认为这可能与仅关键字参数有关,但事实并非如此。当我使用仅关键字参数创建自己的函数时,位置参数和仅关键字参数由 *
(如预期)分隔,而不是 /
。 /
是什么意思?
如 here, the /
as an argument marks the end of arguments that are positional only (see here 所述),即不能用作关键字参数的参数。在 __eq__(self, value, /)
的情况下,斜杠在末尾,这意味着所有参数都被标记为位置,而在 __init__
的情况下,只有自己,即什么都没有,只是位置。
编辑:
这以前仅用于内置函数,但 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
# c, d are positional or keyword
# e, f are 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
help(foo)
交互返回的签名中,一个/
是什么意思?
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.
我认为这可能与仅关键字参数有关,但事实并非如此。当我使用仅关键字参数创建自己的函数时,位置参数和仅关键字参数由 *
(如预期)分隔,而不是 /
。 /
是什么意思?
如 here, the /
as an argument marks the end of arguments that are positional only (see here 所述),即不能用作关键字参数的参数。在 __eq__(self, value, /)
的情况下,斜杠在末尾,这意味着所有参数都被标记为位置,而在 __init__
的情况下,只有自己,即什么都没有,只是位置。
编辑:
这以前仅用于内置函数,但 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
# c, d are positional or keyword
# e, f are 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