猿问

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

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


例如,在以下代码中,无法在运行时评估 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

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


宝慕林4294392
浏览 238回答 2
2回答

ibeautiful

就像错误所说的那样:Error:positional argument follows keyword argument关键字参数后面不能有位置参数。你的例子就是一个很好的例子。您将第一个参数指定为关键字参数。所以解释器现在如何解释参数的顺序是不明确的。第二个参数是否成为第一个参数?第二个参数?但是您已经指定了第一个参数 ( firstname='John') 那么位置参数会发生什么?def student(firstname, standard,lastname): print(firstname, lastname, 'studies in', standard, 'Standard')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')祝你在调试什么参数匹配什么参数时好运。

茅侃侃

也许你应该尝试:student('John', 'Gates', 'Stevehn')我不知道你是否可以在调用函数的同时定义一个变量。悉尼
随时随地看视频慕课网APP

相关分类

Python
我要回答