首页 > 解决方案 > 避免传递太多参数

问题描述

我有以下代码,我需要将所有参数从一个函数传递到另一个函数。我想知道一种避免长长的论点的方法。我只“知道”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)

标签: python

解决方案


编写一个类,将参数放入__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. 有很多代码模式你不需要重写。

推荐阅读