Python Function Parameter Matching Model General Rule keyword only Parameter Details
- 2021-06-28 09:32:45
- OfStack
Python3 has a more general collation for function parameters, the Python3 keyword-only parameter, which is a parameter that must be passed by keyword only and not populated by a position parameter.This rule is useful for dealing with more than one parameter for a person.
keyword-only
kword_only(1, 2, 3, c=4)
print('-' * 20)
kword_only(a=1, c=3)
Example results:
1 (2, 3) 4
--------------------
1 () 3
Parameters after *args need to be passed in the call using a keyword or an exception will be thrown.
def kword_only(a, *b, c):
print(a, b, c)
kword_only(1, 2, 3)
Exceptional results:
kword_only(1, 2, 3)
TypeError: kword_only() missing 1 required keyword-only argument: 'c'
We can also use a * character in the parameter list to indicate that the function does not accept a parameter list of variable lengths, but requires that the parameters after * be passed using keyword parameters.
def kword_only(a, *, b, c):
print(a, b, c)
kword_only(1, b=2, c=3)
print('-'*20)
kword_only(b=2, c=3, a=1)
Example results:
1 2 3
--------------------
1 2 3
We can see that a can be passed using location parameters, but b, c must be passed through keyword parameters or an exception will be thrown.
def kword_only(a, *, b, c):
print(a, b, c)
kword_only(1, 2, 3)
Exceptional results:
kword_only(1, 2, 3)
TypeError: kword_only() takes 1 positional argument but 3 were given
Of course, we can use the default value for the keyword-only parameter so that the a in this example can still be passed by location or keyword parameters, while b and c are optional, and of course, keyword parameters are still used to pass if necessary.
def kword_only(a, *, b=2, c=3):
print(a, b, c)
kword_only(1)
print('-'*20)
kword_only(a=1)
print('-'*20)
kword_only(b=22, c=33, a=11)
Example results:
1 2 3
--------------------
1 2 3
--------------------
11 22 33
summary