避免传递太多参数

时间:2019-03-27 22:05:31

标签: python

我有以下代码,需要将所有参数从一个函数传递给另一个函数。我想知道一种避免参数过多的方法。我只“知道” Python中有“ *”和“ **”,但是我以前从未使用过它们。

# definition
    def TestCase(test_name, op_type, input_shapes, op_args, run_mode):
        # all those arguments are unchanged before passing to 
        # "add_tester"
         ...

        # another function, the long list of arguments doesn't look 
        # good to me  
        add_tester("c2", test_name, input_shapes, op_args, run_mode, benchmark_func)

# Call TestCase
TestCase(
test_name='mm',
op_type='MM',
input_shapes=input_shapes,
op_args={'trans_a': trans_a, 'trans_b': trans_b},
run_mode=run_mode)

3 个答案:

答案 0 :(得分:1)

编写一个类,在__init__中放入参数,然后使用self

class TestCase:
    def __init__(self, test_name, op_type, run_mode, benchmark_func):
        self._test_name = test_name
        self._op_type = op_type
        self._run_mode = run_mode
        self._benchmark_func = benchmark_func
        # bunch of initiation code follows

    # another function, the long list of arguments doesn't look 
    # good to me  
    def run_test(self, op_args, idk_what_this_is="c2"):
        # access self._XX for the fields

一些注意事项:

  1. 请谨慎使用命名约定。将小写字母与下划线一起用于函数/方法。
  2. 如果您要进行常规测试,请考虑使用现有的框架,例如nose。这样做无需重写很多代码模式。

答案 1 :(得分:0)

如果您对如何使用*和**表示法感兴趣,请查看示例:

def f(a, *args, **kwargs):
     print("a: %s, args: %s, kwargs: %s" % (a,args, kwargs))

f(1, 2, 3, 4, b=5, c=6, d=7)
# output: A: 1, args: (2, 3, 4), kwargs: {'b': 5, 'c': 6, 'd': 7}

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?对此有很好的解释。

对于您的代码,如果您不想一一传递所有参数,则可以对所有变量使用** kwargs:

# definition
def TestCase(**kwargs):
    # all those arguments are unchanged before passing to 
    # "add_tester"
     ...

    # another function, the long list of arguments doesn't look 
    # good to me  
    add_tester("c2", kwargs)

# Call TestCase
TestCase(test_name='mm', op_type='MM', input_shapes=input_shapes, op_args={'trans_a': trans_a, 'trans_b': trans_b}, run_mode=run_mode)

但是您需要将参数称为kwargs['test_name'], kwargs['op_type'], ...,并且参数变为可选参数,无论谁调用您的方法,都不会看到期望的实际参数。

答案 2 :(得分:0)

您可以使用全局变量。全局变量是在函数外部定义和声明的变量,我们需要在函数内部使用它们。 GeeksforGeeks有一些示例:https://www.geeksforgeeks.org/global-local-variables-python/ 还有配置文件。在单个程序中的各个模块之间共享信息的规范方法是创建一个特殊的模块(通常称为config或cfg)。只需将config模块导入应用程序的所有模块中即可;然后该模块就可以作为全局名称使用。参见python常见问题解答:https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules