[英]how to make *args optional in python when **kwargs is given?
I have this code: 我有以下代码:
class Test(object):
def f1(self,*args,**kwargs):
print args
print kwargs
self.f2(*args,**kwargs)
def f2(self,*args,**kwargs):
print "calling f2"
print "args= ",args
print "kwargs= ",kwargs
t = Test()
args = [1,2,3]
kwargs= {'a':1,'b':2}
t.f1(args,kwargs)
#second call
t.f1(kwargs)
and it prints 它打印
([1, 2, 3], {'a': 1, 'b': 2})
{}
calling f2
args= ([1, 2, 3], {'a': 1, 'b': 2})
kwargs= {}
({'a': 1, 'b': 2},)
{}
calling f2
args= ({'a': 1, 'b': 2},)
kwargs= {}
I want to make *args
in the construct optional. 我想使结构中的
*args
为可选。 That is if I pass dict
, it is taken as args
in the second call above. 也就是说,如果我传递
dict
,则在上面的第二个调用中将其作为args
。 I do not want that. 我不要那个。 I basically want this construct:
f1(*args,**kwargs)
我基本上想要这个构造:
f1(*args,**kwargs)
-- if *args
is present, then process *args
if it is not present, then process **kwargs
, but do not take the dict passed to be *args
That is because I will not be passing dict
to *args
in any case. -如果
*args
存在,则处理*args
如果不存在),然后处理**kwargs
,但不要将传递给*args
的字典作为*args
这是因为无论如何我都不会将dict
传递给*args
。
t = Test()
args = [1,2,3]
kwargs= {'a':1,'b':2}
t.f1(args,kwargs)
t.f1(kwargs)
Needs to be 需要是
t = Test()
args = [1,2,3]
kwargs= {'a':1,'b':2}
t.f1(*args,**kwargs)
t.f1(**kwargs)
Otherwise it passes args
and kwargs
as the first and second argument (which both get collapsed to *args
inside the function) 否则,它将
args
和kwargs
作为第一个和第二个参数传递(这两个*args
在函数内部都折叠为*args
)
You had argument unpacking correct, but hadn't added the proper syntax for argument packing . 您的参数解 压缩正确,但是没有为参数压缩添加正确的语法。
You're doing it wrong. 你这样做是错的。
t.f1(*args, **kwargs)
t.f1(**kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.