Python2函数,默认参数报SyntaxError
本文介绍了Python2函数,默认参数报SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
问题
想弄清楚默认参数
,*args
,kwargs
,如果混用,会怎样,但是报错(不明白它的报错含义)
表层问题描述在代码旁边了
更加深入的问题是: Python的形参是如何放置的? 传入的时候有什么讲究?
或: 是否有一篇文章,深入地从底层机制讲解这方面的问题?
相关代码
代码1
以下函数报: TypeError: testfunc() got multiple values for keyword argument 'a'
def testfunc(a=1, b=2, c=3, d=4, *args):
print a
print b
print c
print d
args = (1, 2, 3, 4)
# 根据默认参数的定义
# 一般我们认为: 想怎么传就怎么传
# 但是: 结果不是我们想象的那样, 因为报错了
testfunc(a=10, b=20, c=30, d=40, *args)
testfunc(a=10, c=30, *args)
testfunc(*args)
testfunc(d=1, *args)
def test2(a=1, b=2, c=3, d=4, *args, **kwargs):
print a
print b
print c
print d
args = (1, 2, 3, 4)
kwargs = {'a': 1, 'b':2}
test2(a=10, *args, **kwargs)
代码2
# 试试不加*args, **kw这些会怎样?
# 果然, 爱怎么传,就怎么传
def func(a=1, b=2, c=3, d=4):
print a
print b
print c
print d
func(d=1, c=2, b=3, a=4)
func()
func(b=4, a=1)
# 这样呢?
# 仍然不报错
def func(a, b=2, c=3, d=4):
print a
print b
print c
print d
func(d=1, c=2, b=3, a=4)
func(b=4, a=1)
# 加入*args后呢?
# 会报错
def func(a, b=2, c=3, d=4, *args):
print a
print b
print c
print d
print args
func(d=1, c=2, b=3, a=4)
func(b=4, a=1)
func(1, 2, 3, 4, 5, 6)
func(1, b=2, d=4, 5, 6, 7) # error
func(1, b=2, c=3, d=4, 5, 6, 7) #error
# 加入**kwargs呢, 不做举例了
至此, 可以总结点经验
1. *args, **kw对默认参数似乎有影响
2. 默认参数能乱序,但是在某些情况下
所以, 我才想要一个深层次的解答, 为上面的经验提供理论证明
重现
拷贝代码,运行之
报错信息
TypeError: testfunc() got multiple values for keyword argument 'a'
上下文环境
Python2
windows7
尝试解决
解决方案
的确是你调用函数的错误,应该是testfunc(10, 20, 30, 40, *args),
想了解具体可参照:
http://docs.pythontab.com/int...
或者Python cookbook中关于默认参数的设置:
http://python3-cookbook.readt...
这篇关于Python2函数,默认参数报SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文