Keyword parameters refer to using the names of formal parameters to determine the input parameter values. When specifying function actual parameters in this way, it no longer needs to be exactly the same as the position of the formal parameters, as long as the parameter names are written correctly.
Therefore, the parameter names of Python functions should have better semantics, so that the program can immediately understand the meaning of each parameter passed into the function.
For example, in the following program, the form of keyword parameters is used to pass parameters to the function:
def dis_str(str1,str2): print("str1:",str1) print("str2:",str2) #位置参数 dis_str("http://c.biancheng.net/python/","http://c.biancheng.net/shell/") #关键字参数 dis_str("http://c.biancheng.net/python/",str2="http://c.biancheng.net/shell/") dis_str(str2="http://c.biancheng.net/python/",str1="http://c.biancheng.net/shell/")
The program execution result is:
str1: http ://c.biancheng.net/python/
str2: http://c.biancheng.net/shell/
str1: http://c.biancheng.net/python/
str2: http://c.biancheng.net/shell/
str1: http://c.biancheng.net/shell/
str2: http://c.biancheng.net/python/
It can be seen that when calling a parameterized function, it can be called based on positional parameters or using keyword parameters (line 8 in the program). When calling using keyword parameters, you can change the position of the parameter at will.
Of course, you can also use a mixture of positional parameters and keyword parameters to pass parameters like the 7th line of code. However, it should be noted that when passing parameters in a mixed manner, the keyword parameters must be located after all positional parameters. In other words, the following code is wrong:
# 位置参数必须放在关键字参数之前,下面代码错误 dis_str(str1="http://c.biancheng.net/python/","http://c.biancheng.net/shell/")
The Python interpreter will report the following error:
SyntaxError: positional argument follows keyword argument
The above is the detailed content of What are the keyword parameters of Python functions and how to use them?. For more information, please follow other related articles on the PHP Chinese website!