在Python中,函数参数列表中的斜杠(/)表示分隔位置参数和关键字参数的界限

2023年 8月 29日 61.0k 0

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 Function
def demo(myStr):
print("Car =: ",myStr)

# function call
demo("BMW")
demo("Tesla")

登录后复制

输出

Car =: BMW
Car =: 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 Function
def demo(myStr):
print(help(divmod))

# function call
demo("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)

登录后复制

输出

在Python中,函数参数列表中的斜杠(/)表示分隔位置参数和关键字参数的界限

In the above example, an error occurred since the divmod() takes no keyword arguments.

以上就是在Python中,函数参数列表中的斜杠(/)表示分隔位置参数和关键字参数的界限的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论