如何在python的用户定义函数中实现“仅位置参数”?

Dam*_*ahu 5 python parameters function python-3.x pep570

如何为用户在 python 中定义的函数实现“仅位置参数”?

def fun(a, b, /):
    print(a**b)

fun(5,2)        # 25
fun(a=5, b=2)   # should show error
Run Code Online (Sandbox Code Playgroud)

Eug*_*ash 7

在 Python 3.8 之前,/语法只是文档性的。从3.8开始,您可以使用它在函数定义中指定仅位置参数。例子:

def pow(x, y, z=None, /):
    r = x**y
    if z is not None:
        r %= z
    return r
Run Code Online (Sandbox Code Playgroud)

现在pow(2, 10)pow(2, 10, 17)是有效的调用,但是pow(x=2, y=10)pow(2, 10, z=17)是无效的。

有关更多详细信息,请参阅PEP 570


che*_*ner 4

更新:这个答案将变得越来越过时;请参阅/sf/answers/3930436541/


唯一的解决方案是使用*- 参数,如下所示:

def fun(*args):
    print(args[0] ** args[1])
Run Code Online (Sandbox Code Playgroud)

但这也有其自身的问题:您不能保证调用者将提供恰好两个参数;你的函数必须准备好处理 0 或 1 个参数。(忽略额外的参数很容易,所以我不会详细说明这一点。)