问题
What is the meaning of the square brackets inside the round brackets of a function in the Python documentation?
E.g.:
help([object])
or
int([x[, base]])
回答1:
Everything that is in square brackets is optional, i.e. you can omit it. If the square brackets contain more than 1 argument, you can't choose which ones to omit, you must either specify all of them, or none.
That's where nested brackets come in handy:
int([x[, base]])
Here, for example, you can use int()
without arguments (by omitting the whole outer bracket) or int(x)
(by omitting the inner bracket) or int(x, base)
. But not int(base)
(well, that would just mean int(x)
).
This isn't actual Python syntax, just a way for documentation to be clearer. Python 3's documentation tries to avoid these brackets.
回答2:
These are optional arguments. You need not specify them, but you may want to use them for specific functionality.
When one or more top-level parameters have the form parameter = expression, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. If a parameter has a default value, all following parameters must also have a default value — this is a syntactic restriction that is not expressed by the grammar.
source
来源:https://stackoverflow.com/questions/10053286/intx-base-square-brackets-in-functions-in-python-documentation