Python - 位置参数



位置参数

Python 中,可以定义一个 函数,其中一个或多个参数不能使用关键字接受其值。这些参数称为 位置参数

要使参数成为位置参数,请使用正斜杠 (/) 符号。此符号之前的全部参数都将被视为位置参数。

Python 的 内置 input() 函数 是位置参数的一个示例。input 函数的语法为:

input(prompt = "")

Prompt 是一个解释性字符串,供用户参考。但是,您不能在括号内使用 prompt 关键字。

示例

在这个例子中,我们使用了 prompt 关键字,这将导致错误。

name = input(prompt="Enter your name ")

执行此代码后,将显示以下错误消息:<>

   name = input (prompt="Enter your name ")
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: input() takes no keyword arguments

位置参数示例

让我们通过一些示例来了解位置参数:

示例 1

在这个例子中,我们通过在结尾处添加 "/" 将 intr() 函数 的两个参数都设置为位置参数。

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

运行代码后,将显示以下结果:

12648.0

示例 2

如果尝试将参数作为关键字使用,Python 将引发错误,如下例所示。

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

运行此代码后,将显示以下错误消息:

   interest = intr(amt=1000, rate=10)
              ^^^^^^^^^^^^^^^^^^^^^^^
TypeError: intr() got some positional-only arguments passed as keyword arguments: 'amt, rate'

示例 3

可以这样定义函数:它有一些仅限关键字的参数和一些仅限位置的参数。这里,x 是必需的位置参数,y 是常规位置参数,z 是仅限关键字参数。

def myfunction(x, /, y, *, z):
   print (x, y, z)
   
myfunction(10, y=20, z=30)
myfunction(10, 20, z=30)

上述代码将显示以下输出:

10 20 30
10 20 30 
广告
© . All rights reserved.