为什么 Python 函数文档在可选参数的括号后面包含逗号?
Python 文档中函数签名的格式有点令人困惑。将逗号放在开括号后面而不是之前有什么意义?嵌套括号有什么意义?
它们怎么样:
RegexObject.match(string[, pos[, endpos]])
我期望以下之一:
RegexObject.match(string, [pos], [endpos])
RegexObject.match(string[, pos][, endpos])
The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What is the significance of nesting the brackets?
How they are:
RegexObject.match(string[, pos[, endpos]])
I would expect one of the following:
RegexObject.match(string, [pos], [endpos])
RegexObject.match(string[, pos][, endpos])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为否则正确的语法是包含逗号,即使您忽略参数。方括号内的部分是可选的,因此通过将逗号移出方括号,它们就不再是可选的。例如,要仅使用字符串调用下面的函数:
我必须这样做:
但是,这不是很优雅。
Because otherwise the correct syntax would be to include the comma even if you are ignoring the arguments. The parts inside the square brackets are optional, so by moving the commas out of the square brackets, they are no longer optional. For example, to call the function below with only a string:
I would have to do:
But, that isn't very elegant.
括号意味着您可以省略它们之间的部分。因此,如果文档按照您建议的方式编写,则意味着您可以通过将所有内容保留在括号中来编写 RegexObject.match(string,,) 。或者 RegexObject.match(string,,endpos) 省略第二个。但你不能。如果省略 endpos,则还必须省略其前面的逗号。如果省略 pos,则必须省略其前面的逗号以及 endpos。因此,它的编写方式可以清楚地表明这一点。
The brackets mean that you can leave out the part between them. So if the docs would be written the way you suggest, it would imply that you can write RegexObject.match(string,,) by leaving everything in brackets. Or RegexObject.match(string,,endpos) by just leaving out the second one. But you can't. If you leave out endpos, you also have to leave out the comma before it. And if you leave out pos, you have to leave out the comma before it as well as endpos. So it's written in a way that makes that clear.
如果您考虑一下包围参数列表的所有可选组件的方括号,它就更有意义了。本质上,用户可以自行决定省略括号内的任何内容。
If you think about the brackets enclosing all optional components of the argument list, it makes more sense. Essentially, anything inside brackets may be left out at the discretion of the user.
方括号表示内容是可选的,但方括号之外的内容是强制性的。
用您的符号:
我希望必须写:
嵌套是必需的,因为如果您提供第三个参数,那么您还必须提供第二个参数,即使它是可选参数。以下非嵌套替代方案将是不明确的:
The square bracket means that the contents are optional, but everything outside of square brackets is compulsory.
With your notation:
I would expect to have to write:
The nesting is required because if you supply the third parameter then you must also supply the second parameter even though it is an optional parameter. The following non-nested alternative would be ambiguous:
左括号表示可选参数。如果逗号位于括号之外,即使您不想使用
pos
参数(例如),您也必须键入它。The open bracket indicates an optional argument. If the comma were outside the bracket, you would have to type it even if you didn't want to use the
pos
argument (for example).