使用kwargs将参数传递给函数 - Python

时间:2015-03-04 17:24:54

标签: python

我有以下代码段:

kwargs = {'inventory_file' : self.inventory_file}
for ts in self.test_sets_list:
   current_ts = TestSet(name=ts,
                        test_cases=self.test_sets_list[ts],
                        om_ip_address=self.om_ip_address,
                        **kwargs)


class TestSet(object):
   def __init__(self, name, test_cases, om_ip_address, **kwargs):


class TestCase(object):
        def __init__(self, parameters, config_file, test_failure,
                 om_ip_address, **kwargs):

我知道我可能做错了,因为在**kwargs我正在解冻kwargs中的值。我想要的是将kwargs的参数一直传递给TestCase。在TestSet内部,我试图传递kwargs参数:

instance = TestCase(parameters=params, 
                    config_file=cnf,
                    om_ip_address=om_ip_address,
                    **kwargs)

但是我收到以下错误:

Traceback (most recent call last):
  File "main.py", line 258, in <module>
    main(args)
  File "main.py", line 217, in main
    operation.collect_tests()
  File "main.py", line 157, in collect_tests
    **kwargs)
  File "test_set.py", line 47, in __init__
    self.__instantiate_module(tc, om_ip_address)
  File "test_set.py", line 78, in __instantiate_module
    **self.kwargs)
TypeError: __init__() got an unexpected keyword argument 'inventory_file

该类通过以下方式实例化:

    my_class = getattr(module, test_cases['name'])
    instance = my_class(parameters=params, 
                        config_file=cnf,
                        om_ip_address=om_ip_address)

我怎样才能将kwargs一直传递给TestCase

1 个答案:

答案 0 :(得分:1)

使用**kwargs调用函数,其中kwargs = {'inventory_file' : self.inventory_file}与调用

相同
function(inventory_file=self.inventory_file)

如果function的定义在接受的参数列表中没有inventory_file,它将抛出你在那里得到的错误。 解决这个问题的两种方法:

class TestCase(object):
    # add inventory_file to the params list with a default value
    def __init__(self, parameters, config_file, test_failure,
             om_ip_address, inventory_file=None, **kwargs):
        self.inventory_file = inventory_file

或:

class TestCase(object):
    # check for the inventory file in the kwargs dict
    def __init__(self, parameters, config_file, test_failure,
             om_ip_address, **kwargs):
        if 'inventory_file' in kwargs:
             self.inventory_file = kwargs['inventory_file']

并且在两种情况下:

>>> t = TestCase('param1','param2','param3','param4', **{'inventory_file':'file'})
>>> t.inventory_file
'file'