简体   繁体   English

需要澄清可选参数

[英]Need clarification on optional parameters

range(start, stop[, step])

what does these square brackets and comma means exactly? 这些方括号和逗号到底是什么意思? I know that step is optional parameter, but the concept is still not clear to me It would be great if you can provide some good examples so that next time these brackets in python doc doen't horrify me 我知道step是可选参数,但是对我来说这个概念仍然不清楚,如果您可以提供一些很好的示例,那么下次python doc中的这些括号不会让我感到恐惧

Thanks! 谢谢!

The square brackets are an old syntax-documentation shorthand for "part in brackets can be omitted." 方括号是“可以省略部分括号”的旧语法文档缩写。 So by putting both the second , and step in brackets, it's saying you can keep both or omit both, but keeping the , and omitting step (or vice versa) is a syntax error. 因此,通过将两个第二,step在括号中,它说,你可以保留两个或省略两个,但保持,并省略step (反之亦然)是一个语法错误。

Another syntax-documentation shorthand you sometimes see is <parameter> , which means to put the parameter's value (or a variable or expression; whatever works) where the text is. 您有时会看到的另一种语法文档速记形式是<parameter> ,这意味着将参数的值(或变量或表达式;无论如何起作用)放在文本所在的位置。 The <> are not kept. <>不保留。 These brackets are used to disambiguate parameters from keywords and function names. 这些括号用于区分关键字和函数名称中的参数。

And another shorthand is ... , which means "the part before this can be repeated as needed." 另一个简写是... ,它表示“此之前的部分可以根据需要重复”。

Putting it all together, you could document the max function as: 放在一起,您可以将max函数记录为:

max(<value> [, <value> ...])

which means the literal function name max followed by a literal ( then a value; then optionally a , and another value, repeated as needed, and ending with a literal ) . 这意味着字面函数名max后跟一个文字(然后的值;然后任选地,和其他值,根据需要,并用文字结束重复)

It's easier to read than BNF-type syntaxes, though less precise, and it works even if you only have a plain text format and thus can't set keywords and literals in a different typeface. 它比BNF类型的语法更易于阅读,尽管精确度较低,并且即使您只有纯文本格式,因此也无法以不同的字体设置关键字和文字,它仍然可以工作。

It means that even if you don't specify the step argument, a default value will be used. 这意味着即使您不指定step参数,也将使用默认值。 In this case the default value is 1 . 在这种情况下,默认值为1 The square brackets are just a python convention to indicate optional arguments. 方括号只是表示可选参数的python约定。

You can override the default value by explicitly specifying the step. 您可以通过明确指定步骤来覆盖默认值。

>>> range(0, 10, 2)
[0, 2, 4, 6, 8]

It means you can call the range function with/without step argument. 这意味着您可以使用/不使用step参数来调用range函数。

>>> range(1, 5, 1) # with `step` argument
[1, 2, 3, 4]
>>> range(1, 5)    # without `step` argument
[1, 2, 3, 4]

So, above two example both works. 因此,以上两个示例均有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM