函数声明时,位置参数与默认参数不可穿插。
更明确的说,位置参数必须在默认参数前面。
不然会报错,SyntaxError: non-default argument follows default argument
通过<变量名=值>的方法赋值,可能会与位置对应赋值冲突
通过<变量名=值>的方法赋值,造成可变参数无法赋值。详细说,要给可变参数赋值,位置参数和默认参数,只能用位置对应的方式赋值,不能用<变量名=值>。
声明时:SyntaxError: non-default argument follows default argument
调用时:SyntaxError: positional argument follows keyword argument
调用时:TypeError: getValue() got multiple values for argument ‘position1’
def getValue(position1, position2, default1 = "默认"):print(position1, position2, default1)
def getValue(default1 = "默认", position1, position2):print(position1, position2, default1)
def getValue(position1, default1 = "默认", position2):print(position1, position2, default1)
函数声明时,位置参数与默认参数不可穿插。
更明确的说,位置参数必须在默认参数前面。
不然会报错,SyntaxError: non-default argument follows default argument
def getValue(position1, position2, default1 = "默认"):print(position1, position2, default1)
getValue("matchPosition1", "matchPosition2", "matchDefault")
getValue("matchPosition1", "matchPosition2", default1 = "matchDefault")
getValue("matchPosition1", position2 = "matchPosition2", default1 = "matchDefault")
getValue(position1 = "matchPosition1", position2 = "matchPosition2", default1 = "matchDefault")
getValue(position1 = "matchPosition1", position2 = "matchPosition2", default1 = "matchDefault")
getValue(position1 = "matchPosition1", default1 = "matchDefault", position2 = "matchPosition2")
getValue(position2 = "matchPosition2", position1 = "matchPosition1", default1 = "matchDefault")
getValue(position2 = "matchPosition2", default1 = "matchDefault", position1 = "matchPosition1")
getValue(default1 = "matchDefault", position1 = "matchPosition1", position2 = "matchPosition2")
getValue(default1 = "matchDefault", position2 = "matchPosition2", position1 = "matchPosition1")
matchPosition1 matchPosition2 matchDefault
getValue(position1 = "matchPosition2", "matchPosition1")
getValue("matchPosition1", position1 = "matchPosition1")
位置参数通过<变量名=值>的方法赋值,可能会与位置对应赋值规范冲突,造成:
语法错误:SyntaxError: positional argument follows keyword argument
重复错误:TypeError: got multiple values for argument ‘position1’
def getValue(position1, position2, default1 = "默认", *args):print(position1, position2, default1, args)
getValue("matchPosition1", "matchPosition2", "matchDefault", "matchArgs1", "matchArgs2")
解决办法参见:《Python:函数:关键字参数:巧用关键字参数----隐藏默认值 (解答:好多内置函数,修改默认值需要通过“形参变量名=值”的方式) 》
getValue("matchPosition1", "matchPosition2", default1 = "matchDefault","matchArgs1", "matchArgs2")
要给可变参数赋值,位置参数和默认参数,只能用位置对应的方式赋值,不能用<变量名=值>。
声明时候,严格按照顺序;调用时候,位置参数与默认值参数类似,都最好通过位置对应的方式赋值,不用<变量名=值>,拓展性强,避免不必要的错误。
参见
可变参数(*args)后
不带默认值
参见
本文发布于:2024-02-03 23:18:00,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170697351851508.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |