我有一个字典(arguments_fun),带有要传递给函数(fun)的参数。在Example1中,代码有效:
class Example1:
arguments_fun={'a': 2, 'b': 3, 'c': 4} #substitute this into function arguments
def fun (self, **kwargs):
print(kwargs['a'], kwargs['b'], kwargs['c'])
a=Example1()
a.fun(**a.arguments_fun)
Out: 2 3 4
但是我还有一些其他要求:
下面是示例代码:
class Example2:
arguments_fun={'a': 2, 'b': 3, 'c': 4} #substitute this into function arguments
def fun (self, **arguments_fun): #Pass dictionary directly to fun
print(arguments_fun['a'], arguments_fun['b'], arguments_fun['c'])
a=Example2()
a.fun()
a.fun(b=7) #b=7 overrides the arguments_fun value
desired Output:
Out: 2 3 4
Out: 2 7 4
基本上Example2应该像Example3一样工作:
class Example3: #Example 2 shuld work as if it was like this:
def fun (self,a=2, b=3,c=5 ): #Pass dictioary directly to fun
print(a,b, c)
a=Example3()
a.fun()
a.fun(b=7)
Out: 2 3 4
Out: 2 7 4
目的是让我可以编写共享相同参数的其他函数。