SyntaxError 位置参数跟随关键字参数

问题描述 投票:0回答:1

我想知道下面的说法是否正确。

语法错误:位置参数跟随关键字参数

我知道什么是位置参数和关键字参数,但对上面的语句感到困惑。例如当我们说

A 紧随 B 的意思是

//表示“A”在“B”之后

因此,以同样的方式,当我们调用任何函数时,我们应该首先传递 positional 参数,然后传递 keyword 参数。在这种情况下,正确的说法应该是

***SyntaxError: keyword argument follows positional argument***

示例:

    def test(a,b,c):
        print(f"Sum of all no is : {a+b+c}")
    test(a=10,20,c=30)
    test(a=10,20,c=30)
//output                   ^
SyntaxError: positional argument follows keyword argument

示例2:

Passing positional argument first.
    def test(a,b,c):
        print(f"Sum of all no is : {a+b+c}")
    test(20,c=10,b=30)
    //output
    Sum of all no is : 60
python python-3.x syntax-error keyword-argument positional-argument
1个回答
0
投票

这是Python语法的一个特点。它按照位置参数首先出现的顺序解释它们,然后是关键字参数。例如这段代码:

def test(a,b,c):
    print(f"Sum of all no is : {a+b+c}")
test(10,20,a=30)

返回“TypeError: test() 获得参数 'a' 的多个值”。因为 Python 在位置上将 10 和 20 解释为前两个变量,所以已经使用了 'a' 和 'b'

© www.soinside.com 2019 - 2024. All rights reserved.