【发布时间】:2017-06-01 12:54:52
【问题描述】:
我在 spyder 中使用 Python 2.7.13。
def test(a,b,c='c',*args):
for item in args:
print item
此函数定义在 Python 2.7 中有效,但一旦我尝试传入 args,它就会在关键字 arg 之后给出 非关键字 arg 错误:
test(1,2,c='c',10,11)
给出这个:
non-keyword arg after keyword arg
但是这个:
test(1,2,3,4,5)
正在工作。
自从将*args 放在c='c' 之前,我不确定这里有什么问题
def test(a,b,*args,c='c'):
for item in args:
print item
这给了我函数定义的错误。
以上代码只是一个虚拟示例,原始代码如下所示:
def export_plot_as_mat(fname, undersamp, undersamp_type, n_comp, b_s, n_iter, fit_alg, transf_alg, alpha_train, alpha_test, export_info=False, *args):
info = ('undersampling=' + str(undersamp) + ' undersampling_type=' +str(undersamp_type) +
' n_comp=' + str(n_comp) + ' batch_size=' + str(b_s) +
' n_iter=' + str(n_iter) + ' fit_alg=' + str(fit_alg) +
' transform_alg=' + str(transf_alg) + ' alpha_train=' +
str(alpha_train) + ' alpha_test=' + str(alpha_test))
d = [(str(args[i]), args[i]) for i in range(len(args))]
if export_info:
d.append('info',info)
sp.io.savemat(fname + '.mat', d)
我希望可以选择导出用于构建我要导出的数据的参数。
【问题讨论】:
-
更改顺序:
test(1,2,10,11,c='c')。 Python 会做正确的事并收集*args中的所有非关键字参数。 -
@Boldewyn 这可能在 python 3.x 中有效,但在 python 2.7 中这给了我错误
test() got multiple values for keyword argument 'c' -
@PedrovonHertwig 我希望 args 具有不同的大小,这就是为什么我不传递常规参数
-
副本更倾向于 Python 3 解决方案,而 OP 使用的是 Python 2.7。
-
@AryaMcCarthy 因为在这种情况下定义的顺序是正确的,所以这不是同一个问题
标签: python python-2.7 function