Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

python - Keyword only parameter

Reference http://docs.python.org/3/glossary.html#term-parameter

keyword-only parameter: specifies an argument that can be supplied only by keyword. Keyword-only parameters can be defined by including a single var-positional parameter or bare * in the parameter list of the function definition before them, for example kw_only1 and kw_only2 in the following:

def func(arg, *, kw_only1, kw_only2):

Instead of single var-positional parameter shouldn't that be single var-keyword parameter? Maybe i understood something wrong ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you must use either the * bare parameter, or use a single *args parameter, called a var-positional parameter (see the next item in that glossary entry). By adding it to your function signature you force any parameters that follow it to be keyword-only parameters.

So the function signature could be:

def func(positional_arg1, *variable_args, kw_only1, kw_only2):

and variable_args will capture any extra positional arguments passed to the function, or you could use:

def func(positional_arg1, *, kw_only1, kw_only2):

and the function will not support extra positional arguments beyond the first one.

In both cases, you can set kw_only1 and kw_only2 only by using them as keyword arguments when calling func(). Without default values (no =<expression> in their definition) they are still required arguments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...