Python 简明教程

Python - Keyword-Only Arguments

Keyword-Only Arguments

您可以将 variables 用作形式参数列表中的关键字来传递值。使用 keyword arguments 是可选的。但是,您可以强制该函数仅接受关键字参数。您应当在仅关键字参数列表前放置一个星号 (*)。

You can use the variables in formal argument list as keywords to pass value. Use of keyword arguments is optional. But, you can force the function to accept arguments by keyword only. You should put an astreisk (*) before the keyword-only arguments list.

假设我们有一个具有三个参数的函数,我们希望其中的第二个和第三个参数是仅关键字。为此,在第一个参数后放置 *。

Let us say we have a function with three arguments, out of which we want second and third arguments to be keyword-only. For that, put * after the first argument.

Example of Keyword-Only Arguments

built-in print() function 是仅关键字参数的一个示例。您可以提供要打印在括号中的表达式列表。默认情况下,打印的值由一个空格分隔。您可以使用“sep”参数指定其他任意分隔字符。

The built-in print() function is an example of keyword-only arguments. You can give list of expressions to be printed in the parentheses. The printed values are separated by a white space by default. You can specify any other separation character instead using "sep" argument.

print ("Hello", "World", sep="-")

它将打印 −

It will print −

Hello-World

Example: Using "sep" as non-keyword Argument

print() 函数的 sep 参数是仅关键字。尝试将其用作非关键字参数。

The sep argument of the print() function is keyword-only. Try using it as non-keyword argument.

print ("Hello", "World", "-")

您将获得不同的输出,而非所需输出 −

You’ll get different output, not as desired −

Hello World -

Using Keyword-Only argument in User-Defined Method

要想使参数成为仅关键字,在创建用户定义函数时在其前放置星号 (*)。

To make an argument keyword-only, put the astreisk (*) before it while creating the user-defined function.

用户定义函数是指我们在给定类中定义的用来执行特定操作的 Python 函数。它们并非由 Python 预定义。

Those Python functions that are defined by us within a given class to perform certain actions are called as user-defined function. They are not predefined by Python.

Example

在以下用户定义函数“intr()”中,“rate”参数是仅关键字。要调用此函数,rate 的值必须通过关键字传递。

In the following user defined function "intr()" the "rate" argument is keyword-only. To call this function, the value for rate must be passed by keyword.

def intr(amt,*, rate):
   val = amt*rate/100
   return val

interest = intr(1000, rate=10)
print(interest)
100.0

但是,如果您尝试使用默认的位置调用方式来调用上述函数,则会遇到错误。

However, if you try to use the default positional way of calling the above function, you will encounter an error.

Example

以下代码表明在需要仅关键字参数时无法使用位置参数。

The code below shows it is not possible to use positional arguments when keyword-only arguments are required.

def intr(amt, *, rate):
   val = amt * rate / 100
   return val

interest = intr(1000, 10)
print(interest)

执行后,此代码将显示以下结果 −

On executing, this code will show the following result −

interest = intr(1000, 10)
               ^^^^^^^^^^^^^^
TypeError: intr() takes 1 positional argument but 2 were given