This article introduces the Python function parameter types and sorting principle is summarized, the text of the sample code through the introduction of the very detailed, for everyone's learning or work has a certain reference learning value, the need for friends can refer to the following
The parameter problem of functions in Python is a bit complicated, mainly because the parameter type problem leads to more cases, which are analyzed below.
Parameter types: default parameter, keyword parameter, indefinite length positional parameter, indefinite length keyword parameter.
In fact, the total can be divided into positional parameters and keyword parameters, because the positional parameters are placed in the list, the keyword parameters are placed in the dict, Python in the interpretation of the first processing list, did not meet the keyword on the append to the list, encountered the keyword, then begin to do the dict until the end, so the positional parameters must be placed in front of the keyword parameters So, the positional parameter must be placed before the keyword parameter.
Three models are summarized here:
1: When no default function exists:
def test(a,*args,c,d=3,**kwargs): print(a) print(args) print(c) print(d) print(kwargs) test(1,2,3,4,c=1,d=4,e=11,f=22)
Run results:
1 (2, 3, 4) 1 4 {'e': 11, 'f': 22}
2: Default parameters exist, parameters take default values, (default parameters are placed after *args)
def test(a,*args,b=1,c,d=3,**kwargs): print(a) print(args) print(b) print(c) print(d) print(kwargs) test(1,2,3,4,c=1,d=4,e=11,f=22,h=66)
Run results:
(2, 3, 4) 1 {'e': 11, 'f': 22, 'h': 66}
3: Default parameters exist, parameters do not take default values, (default parameters are placed in front of *args)
def test(a,b=1,*args,c,d=3,**kwargs): print(a) print(b) print(args) print(c) print(d) print(kwargs) test(1,2,3,4,c=1,d=4,e=11,f=22,h=66)
Run results:
1 2 (3, 4) 1 4 {'f': 22, 'e': 11, 'h': 66}
Summary:
As you can see from the above, the basic order is actually positional arguments --- > keyword arguments, and then it's a matter of default arguments before and after *args.
One more thing, as already mentioned, keyword arguments are saved as dictionary types, i.e. unordered, but **kwargs need to be placed at the end!
This is the whole content of this article.