【问题标题】:Positional argument follows keyword argument | Error while calling function位置参数跟随关键字参数 |调用函数时出错
【发布时间】:2019-04-23 19:29:03
【问题描述】:

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

例如在以下代码中,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-parameter


【解决方案1】:

正如错误所说:

Error:positional argument follows keyword argument

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

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

您将第一个参数指定为关键字参数。所以现在解释器如何解释参数的顺序是模棱两可的。第二个参数是否成为第一个参数?第二个参数?但是您已经指定了第一个参数 (firstname='John'),那么位置参数会发生什么?

def 学生(名字,标准,姓氏): 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')

祝你好运尝试调试什么参数匹配什么参数。

【讨论】:

  • 同时调用函数?我知道在定义功能时就是这种情况。但这里没有歧义。
【解决方案2】:

也许你应该试试:

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

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

悉尼

【讨论】:

  • 我在调用函数时没有定义变量。你当然可以做这样的学生(firstname ='John',standard='Seventh',lastname='Gates')。这里顺序无关紧要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多