问题描述
我很清楚在Python中使用* args和** kwargs的情况,因此在SO中有很多问题(例如Use of *args and **kwargs和What does ** (double star/asterisk) and * (star/asterisk) do for parameters?)。
但是我想了解的一件事是:为什么不可能同时定义强制性的位置args,强制性的kwarg参数,并最终仍然允许捕获其他args和kwargs,如下面的cant_do_that
一样?
def one_kwarg_is_mandatory(*,b,**kwargs):
print(b)
for key,value in kwargs.items():
print(key,value)
def one_pos_arg_and_one_kwarg_are_mandatory(a,*,**kwargs):
print(a,b)
for key,value)
# I wanted a mandatory arg (a) and possibly parse other args (*args),# then a mandatory kwarg (b) and eventually other kwargs (**kwargs)
def cant_do_that(a,*args,b)
print(args)
for key,value)
# not really interested on this because "b" must be a kwarg and hiding
# it under **kwargs would not be explicit enough for my customer (sometimes myself ;))
def could_do_this_but(a,b)
print(args)
print(kwargs)
是的,可以摆脱b
函数签名中的could_do_this_but
,在函数顶部执行(例如)kwargs.get("b",None)
并在发现{{ 1}} ......但是直接在函数签名上使用“ b”将允许使用该函数进行更快,更明确的代码开发。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)