python - help() 列出方法签名时斜线是什么意思?

标签 python python-3.x parameters introspection

/ 在 Python 3.4 的 help 输出中对于右括号前的 range 是什么意思?

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return a virtual sequence of numbers from start to stop by step.
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.

                                        ...

最佳答案

表示positional only parameters结束,您不能用作关键字参数的参数。在 Python 3.8 之前,此类参数只能在 C API 中指定。

意思是__contains__key参数只能按位置传入(range(5).__contains__(3)),不是作为关键字参数 (range(5).__contains__(key=3)),您可以在纯 python 函数中使用位置参数。

另见 Argument Clinic文档:

To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.

和(最近添加到)Python FAQ :

A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.

语法现在是 Python 语言规范的一部分,as of version 3.8 , 请参阅 PEP 570 – Python Positional-Only Parameters .在 PEP 570 之前,该语法已被保留以备将来可能包含在 Python 中,请参阅 PEP 457 - Syntax For Positional-Only Parameters .

仅位置参数可以使 API 更干净、更清晰,使其他纯 C 模块的纯 Python 实现更加一致且更易于维护,并且由于仅位置参数需要很少的处理,因此它们导致更快的 Python 代码.

关于python - help() 列出方法签名时斜线是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54763710/

相关文章:

javascript - 如何将两个选定的哈希值传递到新 URL,同时保持下拉框中的两个项目处于选中状态

python - 如何动态更改 PuLP 中 LpVariable 的范围?

php - Shell 运行/执行带参数的 php 脚本

python - 互斥体适用于快速的单一作者/缓慢的读者(cpython)?

python - capitalize 函数的较短代码

python - 对包含 B 或 I 标签的连续单词进行分组

python - 类型错误 : Field 'classroom' expected a number but got (4, )

按参数类型转换的 Java 泛型

python - 如何使用 PyCrypto 添加/更改 RSA 私钥的密码

python - pandas 使用 fill_method : Need to know data from which row was copied? 重新采样