how to optimize these python functions?
"我有三个python函数:a()、b()、c(),它们有几乎相同的处理流程,不同的地方只是"x"、"y"、"z",这三个函数只是函数名或变量名的一部分。我怎样才能把这些函数写得既友好又优美呢?"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def a(): do_x() some = var1['x_id'] var2['x_result'] = x_process() ... def b(): do_y() some = var1['y_id'] var2['y_result'] = y_process() ... def c(): do_z() some = var1['z_id'] var2['z_result'] = z_process() ... |
这三个函数基本上是相同的,除了它们调用的函数和它们使用的映射索引。因此,您只需将调用的函数和映射索引作为参数传递给一个统一的函数:
1 2 3 4 5 6 | def do_something(do_fun, id1, id2, process_fun): do_fun() some = var1[id1] var2[id2] = process_fun() do_something(do_x, 'x_id', 'x_result', x_process) |
最好的方法不只是重写这些函数,而是重组它们使用的各种项,将它们从名称中带有x、y或z的变量更改为存储在结构中的项,该结构将字符串"x"、"y"和"z"映射到适当的内容。像这样:
1 2 3 4 5 6 7 8 | do_funcs = {'x': do_x, 'y': do_y, 'z': do_z} # make ids whatever is in var1 # but with the keys as"x","y","z" instead of"x_id","y_id","z_id" ids = {} # make resu;ts whatever is in var2 # but with the keys as"x","y","z" instead of"x_result","y_result","z_result" results = {} processes = {'x': x_process, 'y': y_process, 'z': z_process} |
然后您可以编写一个函数:
1 2 3 4 | def do_stuff(which): do_funcs[which]() some = ids[which] results[which] = processes[which]() |
号
然后你叫
这仅仅是一个草图,因为如何做到最好取决于其他东西的定义和使用方式。不过,其基本思想是不要将部分变量名用作参数。如果你发现自己有一堆叫做
您可以使用lambda函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | def a(): print 'a' def b(): print 'b' def c(): print 'c' def a_process(): print 'a' def b_process(): print 'b' def c_process(): print 'c' def func(x): do = {'a':lambda: a(), 'b':lambda: b(), 'c':lambda:c()} do[x]() some = var1['{}_id'.format(x)] process = {'a':lambda: a_process(), 'b':lambda: b_process(), 'c':lambda:c_process()} var2['{}_result'.format(x)] = process[x]() func('c') |
。