直接将字典作为函数的参数传递

时间:2019-09-30 19:12:44

标签: python dictionary

我有一个字典(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 

但是我还有一些其他要求:

  • 我想直接将arguments_fun作为默认值很有趣。
  • 我希望能够向其传递x个参数,该参数覆盖了arguments_fun值。

下面是示例代码:

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    

目的是让我可以编写共享相同参数的其他函数。

0 个答案:

没有答案
相关问题