位置参数跟随关键字参数 |调用函数时出错[重复]

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

首先,我知道在定义函数时,必须先放置位置参数,然后放置默认参数,以避免解释器出现歧义情况。这就是为什么当我们尝试这样做时,它会抛出错误。

例如在下面的代码中,a和b无法在运行时计算,因此会抛出错误

def func(a=1,b):
    return a+b

func(2)

(

Error:non-default argument follows default argument
)

这是可以理解的。

但是为什么下面的结果会出错呢。它不是在定义函数时发生,而是在调用函数时发生。

def student(firstname, standard,lastname): 
    print(firstname, lastname, 'studies in', standard, 'Standard') 
student(firstname ='John','Gates','Seventh')

Error:positional argument follows keyword argument

我们不能同时传递带关键字和不带关键字的参数吗? [编辑]:问题不是可能的重复,因为重复讨论的是定义默认参数时的情况。我还没有定义它们。我只是问为什么我们不能混合关键字值参数和直接值参数。

python parameters arguments keyword-argument positional-argument
2个回答
1
投票

正如错误所述:

Error:positional argument follows keyword argument

关键字参数后面不能有位置参数。

你的例子就是一个很好的例子。

您将第一个参数指定为关键字参数。因此,解释器现在如何解释参数的顺序是不明确的。第二个参数会成为第一个参数吗?第二个参数?但是您已经指定了第一个参数 (

firstname='John'
),那么位置参数会发生什么情况?

def 学生(名字,标准,姓氏): print(名字, 姓氏, '学习', 标准, '标准')

student(firstname ='John','Gates','Seventh')

解释者将此解释为:

student(firstname ='John',standard='Gates',lastname='Seventh')

student(firstname ='John',standard='Gates',lastname='Seventh')

student(firstname ='John',firstname='Gates',lastname='Seventh')

关于:

student(lastname ='John','Gates','Seventh')

这个?

student(lastname ='John',firstname='Gates',standard='Seventh')

还是这个?

student(lastname ='John',standard='Gates',firstname='Seventh')

祝您调试哪个参数与哪个参数相匹配,祝您好运。


0
投票

也许你应该尝试一下:

student('John', 'Gates', 'Stevehn')

我不知道是否可以在调用函数的同时定义变量。

悉尼

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