在Python中,函数参数列表中的斜杠(/)表示分隔位置参数和关键字参数的界限
a slash in the argument list of a function denotes that the parameters prior to it are positional-only. let us first see a function in python with a parameter −
Function in Python
Example
在这里,我们正在使用参数myStr在Python中创建一个基本函数 -
# Creating a Functiondef demo(myStr): print("Car =: ",myStr)# function calldemo("BMW")demo("Tesla")
输出
Car =: BMWCar =: Tesla
Slash in the parameter list of a function
如上所述,函数参数列表中的斜杠表示其之前的参数是仅位置参数。
在调用接受仅位置参数的函数时,参数将仅根据它们的位置进行映射。
divmode()函数
divmod() 函数是一个函数列表中斜杠的完美示例,即它接受位置参数,如下所示 −
立即学习“Python免费学习笔记(深入)”;
divmod(a, b, /)
上面,由于斜杠位于参数列表的末尾,参数a和b都是位置参数。
Let us print the documentation of divmod() using the help() functiojn in Python
# Creating a Functiondef demo(myStr): print(help(divmod))# function calldemo("BMW")demo("Tesla")
输出
Help on built-in function divmod in module builtins:divmod(x, y, /) Return the tuple (x//y, x%y). Invariant: div*y + mod == x.None
Now, let us see an example of the divmod(). Both the parameters are dividend and divisor −
k = divmod(5, 2)print(k)
输出
(2, 1)
参数列表末尾的斜杠表示两个参数都是位置参数。因此,如果我们使用关键字参数调用divmod(),将会引发错误 −
divmod(a = 5, b = 2)
输出
In the above example, an error occurred since the divmod() takes no keyword arguments.