Python 简明教程
Python - Keyword Arguments
Keyword Arguments
Python 允许以关键字的形式传递函数参数,这些关键字也称为命名参数。 function definition 中的 Variables 作为关键字使用。调用函数时,您可以明确地指定名称及其值。
Python allows to pass function arguments in the form of keywords which are also called named arguments. Variables in the function definition are used as keywords. When the function is called, you can explicitly mention the name and its value.
Calling Function With Keyword Arguments
以下示例演示 Python 中的关键字参数。在第二个函数调用中,我们使用了关键字参数。
The following example demonstrates keyword arguments in Python. In the second function call, we have used keyword arguments.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
# by positional arguments
printinfo ("Naveen", 29)
# by keyword arguments
printinfo(name="miki", age = 30)
它将生成以下 output −
It will produce the following output −
Name: Naveen
Age 29
Name: miki
Age 30
Order of Keyword Arguments
默认情况下,函数按出现的顺序将值分配给参数。但是,在使用关键字参数时,不必遵循函数定义中形式参数的顺序。关键字参数的使用是可选的。您可以使用混合式调用。您可以将值传递给没有关键字的某些参数,而对于其他参数,则使用关键字。
By default, the function assigns the values to arguments in the order of appearance. However, while using keyword arguments, it is not necessary to follow the order of formal arguments in function definition. Use of keyword arguments is optional. You can use mixed calling. You can pass values to some arguments without keywords, and for others with keyword.
Example
让我们尝试借助以下函数定义来理解 −
Let us try to understand with the help of following function definition −
def division(num, den):
quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))
division(10,5)
division(5,10)
由于值分配是按照位置,输出如下 −
Since the values are assigned as per the position, the output is as follows −
num:10 den:5 quotient:2.0
num:5 den:10 quotient:0.5
Example
不要使用位置参数传递值,让我们用关键字参数调用函数 −
Instead of passing the values with positional arguments, let us call the function with keyword arguments −
def division(num, den):
quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))
division(num=10, den=5)
division(den=5, num=10)
与位置参数不同,关键字参数的顺序无关紧要。因此,它将产生以下输出 −
Unlike positional arguments, the order of keyword arguments does not matter. Hence, it will produce the following output −
num:10 den:5 quotient:2.0
num:10 den:5 quotient:2.0
但是,在使用混合调用时,位置参数必须在关键字参数之前。
However, the positional arguments must be before the keyword arguments while using mixed calling.
Example
尝试使用关键字参数以及位置参数调用 division() 函数。
Try to call the division() function with the keyword arguments as well as positional arguments.
def division(num, den):
quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))
division(num = 5, 10)
由于位置参数不能出现在关键字参数之后,Python 会引发以下错误消息 −
As the Positional argument cannot appear after keyword arguments, Python raises the following error message −
division(num=5, 10)
^
SyntaxError: non-keyword arg after keyword arg