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)
解决方案
编写一个类,将参数放入__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
几点注意事项:
- 小心命名约定。函数/方法使用带下划线的小写字母。
- 如果您正在进行常规测试,请考虑现有的框架,例如
nose
. 有很多代码模式你不需要重写。
推荐阅读
- matlab - 如何在 Matlab 中使用索引矩阵分配值?
- php - 如何拯救php中的两个分隔符?
- python - 查找向量化
- spring-boot - 在自定义文件中为 Spring 数据 JPA 定义属性
- apache-kafka-connect - 带有连接 table.include.list 的 Debezium docker 不起作用
- arduino - Arduino:1.8.14(Windows 10),板:“Arduino Uno”
- x86 - 在 qemu (x86_64) 下测量 CPU 周期
- jquery - 如何让布局与同位素插件一起使用?
- mongodb - 如何在mongodb中查询文档的多层
- flutter - 如何转换小部件?到小部件