为什么非默认参数不能跟随默认参数? [英] Why can't non-default arguments follow default arguments?

查看:34
本文介绍了为什么非默认参数不能跟随默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码会抛出 SyntaxError?

 >>>def fun1(a="你是谁", b="True", x, y):... 打印 a,b,x,y...文件<stdin>",第 1 行语法错误:非默认参数跟随默认参数

虽然以下代码运行时没有明显错误:

<预><代码>>>>def fun1(x, y, a="你是谁", b="True"):... 打印 a,b,x,y...

解决方案

所有必需的参数必须放在任何默认参数之前.仅仅因为它们是强制性的,而默认参数不是.从语法上讲,如果允许混合模式,解释器将不可能决定哪些值与哪些参数匹配.如果参数未按正确顺序给出,则会引发 SyntaxError:

让我们看一下使用您的函数的关键字参数.

def fun1(a="你是谁", b="True", x, y):... 打印 a,b,x,y

假设它允许声明函数如上,然后使用上述声明,我们可以进行以下(常规)位置或关键字参数调用:

func1("ok a", "ok b", 1) # 1 是分配给 x 还是 ?func1(1) # 1 是分配给 a 还是 ?func1(1, 2) # ?

您将如何建议在函数调用中分配变量,如何将默认参数与关键字参数一起使用.

<预><代码>>>>def fun1(x, y, a="你是谁", b="True"):... 打印 a,b,x,y...

参考 O'Reilly - Core-Python
因为此函数使用语法正确的默认参数对上述函数调用.关键字参数调用证明能够提供乱序位置参数很有用,但是,加上默认参数,它们也可以用来跳过"缺失的参数.

Why does this piece of code throw a SyntaxError?

  >>> def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y
... 
  File "<stdin>", line 1
SyntaxError: non-default argument follows default argument

While the following piece of code runs without visible errors:

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

解决方案

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

这篇关于为什么非默认参数不能跟随默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆