f(a, b, option1=10, option2=20)
About the basic thing that you want to specify the argument with a keyword like. The option is not specified every time, and if you do not specify it, the default value will be used.
f(a, b) # option1,option2 does not have to be specified
**kwargs
When I search, I often find something called ** kwargs
.
def f(a, b, **kwargs):
option1 = kwargs.get('option1', 1)
option2 = kwargs.get('option2', 2)
kwargs
is a dictionary containing keyword names and values, and the get
method specifies the default value.
However, ** kwargs
is" anything ", so if you inadvertently misspell it, an unintended default value will be used.
f(a, b, opton1=10) #Option1 defaults to 1 due to misspelling
In the first place, Python calls arguments by name, so you shouldn't use ** kwargs
if you know the keywords.
def f(a, b, option1=1, option2=2):
pass
f(a, b, option1=10, option2=20)
f(a, b, opton1=10) #There is no keyword for error opton1
However, ʻoption1` is also a fixed argument, so if you inadvertently make a mistake in the number of arguments, you will overwrite option.
f(a, b, c) #Wrong number of arguments, unintended option1=c
*
Arguments (Python3)In Python3, by inserting *
, the following variables can only be called by keywords.
def f(a, b, *, option1=1, option2=2):
pass
f(a, b, option1=10, option2=20)
f(a, b, c) #Two error fixed variables
f(a, b, opton1=10) #Keywords that do not exist
So this is recommended for Python3.
http://stackoverflow.com/questions/1419046/python-normal-arguments-vs-keyword-arguments
Recommended Posts