Summarize the behavior of python function arguments. Including 3 series.
number | Syntax | function |
---|---|---|
1 | func(value) | Normal call,Function call and argument position are paired |
2 | func(name=value) | Function call corresponding to the keyword |
3 | func(*iterable) | Expand iterable and call function |
4 | func(**dict) | dict key,Expand to value and call function(Pass the argument of 2 as a dict) |
number | Syntax | function |
---|---|---|
1 | def func(name) | Normal function definition,Function call and argument position are paired |
2 | def func(name=value) | Set the initial value in the argument |
3 | def func(*name) | Make the argument a tuple |
4 | def func(**name) | Set the argument to dictionary |
5 | def func(*arg, name) | Only name needs to be specified,3 series only |
6 | def func(*, name=value) | Make all arguments required to be specified,3 series only |
5 and 6 are difficult to understand
In a python function call, it can be called as name = value
, but with only ``` def func (name)
, the function caller can set name = value or pass it only by value. Then, of course, the code will vary.
So, I got a syntax to force it from the 3rd system trying to solve it (probably).
5 can coexist with those that force `` `name = value``` and those that do not. In the following, only c, force the form name = value.
In [18]: def kwonly(a, *b ,c):
....: print(a, b, c)
....:
In [19]: kwonly(1,2,3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-763cbb52b1ed> in <module>()
----> 1 kwonly(1,2,3)
TypeError: kwonly() missing 1 required keyword-only argument: 'c'
#c is name=You can only pass a value by value
In [20]: kwonly(1, 2, c=3)
1 (2,) 3
It's almost the same as 5, but let's set all to name = value and decide the default value. Of course, there is no need for the default value. You can also set the default value.
In [21]: def kwonly2(*, b , c=3):
....: print(b,c)
....:
In [22]: kwonly2(1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-ace6c6f57de4> in <module>()
----> 1 kwonly2(1)
TypeError: kwonly2() takes 0 positional arguments but 1 was given
#1 is not recognized as an argument in the first place
In [23]: kwonly2(b=1)
1 3
In [24]: kwonly2(b=1,2)
File "<ipython-input-24-6c15c1f279e8>", line 1
kwonly2(b=1,2)
^
SyntaxError: non-keyword arg after keyword arg
#c is name=Can only be passed by value(Of course b too)
In [25]: kwonly2(b=1,c=2)
1 2
Recommended Posts