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 pythonexample在这里,我们正在使用参数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() 函数是一个函数列表中斜杠的完美示例,即它接受位置参数,如下所示 −
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.
以上就是在python中,函数参数列表中的斜杠(/)表示分隔位置参数和关键字参数的界限的详细内容。