Python 简明教程
Python - Positional-Only Arguments
Positional Only Arguments
It is possible in Python to define a function in which one or more arguments can not accept their value with keywords. Such arguments are called positional-only arguments.
要将参数设为仅位置,请使用正斜杠 (/) 符号。该符号之前的所有参数都将被视为仅位置。
To make an argument positional-only, use the forward slash (/) symbol. All the arguments before this symbol will be treated as positional-only.
Python 的 built-in input() function 是仅位置参数的示例。input 函数的语法为 −
Python’s built-in input() function is an example of positional-only arguments. The syntax of input function is −
input(prompt = "")
提示是供用户受益的解释性字符串。但是,你不能在圆括号内使用 prompt 关键字。
Prompt is an explanatory string for the benefit of the user. However, you cannot use the prompt keyword inside the parentheses.
Example
在此示例中,我们正在使用 prompt 关键字,这会导致错误。
In this example, we are using prompt keyword, which will lead to error.
name = input(prompt="Enter your name ")
执行此代码时,将显示以下错误消息 −<>
On executing, this code will show the following error message −<>
name = input (prompt="Enter your name ")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: input() takes no keyword arguments
Positional-Only Arguments Examples
让我们借助一些示例来理解仅位置参数 −
Let’s understand positional-only arguments with the help of some examples −
Example 1
在此示例中,我们通过在末尾放置“/”将 intr() 函数的两个参数设为仅位置。
In this example, we make both the arguments of intr() function as positional-only by putting "/" at the end.
def intr(amt, rate, /):
val = amt * rate / 100
return val
print(intr(316200, 4))
运行该代码后,将显示以下结果 −
When you run the code, it will show the following result −
12648.0
Example 2
如果我们尝试使用参数作为关键字,Python 会引发错误,如以下示例所示。
If we try to use the arguments as keywords, Python raises errors as shown in the below example.
def intr(amt, rate, /):
val = amt * rate / 100
return val
print(intr(amt=1000, rate=10))
运行此代码后,将显示以下错误消息 −
On running this code, it will show following error message −
interest = intr(amt=1000, rate=10)
^^^^^^^^^^^^^^^^^^^^^^^
TypeError: intr() got some positional-only arguments passed as keyword arguments: 'amt, rate'
Example 3
该函数可以按特定的方式定义,以便具有某些仅关键字和某些仅位置的参数。在此,x 是必需的仅位置参数,y 是常规位置参数,而 z 是仅关键字参数。
A function may be defined in such a way that it has some keyword-only and some positional-only arguments. Here, x is a required positional-only argument, y is a regular positional argument, and z is a keyword-only argument.
def myfunction(x, /, y, *, z):
print (x, y, z)
myfunction(10, y=20, z=30)
myfunction(10, 20, z=30)
以上代码将显示以下输出 −
The above code will show the following output −
10 20 30
10 20 30