2 回答
TA贡献1828条经验 获得超3个赞
理想情况下,您将传递函数本身而不是状态变量,但由于这是遗留代码,因此不更改接口的一种解决方案是设置函数字典,如下所示:
def func(infile, some_other_data, outfile, status_variable,
status_functions={
'status_A': function_A,
'status_B': function_B,
}
):
try:
status_function = status_functions[status_variable]
except KeyError:
status_function = lambda line, element: None
with open(infile, 'r') as f, open(outfile, 'w') as outf:
for line in f:
# parse line
for element in some_other_data:
standard_function(line, element)
status_function(line, element)
# handle other possible status variables
outf.write(new_line)
TA贡献1946条经验 获得超4个赞
如果status_variable-> function_name之间有直接对应关系,并且所有调用都是常规调用:function(line, element)您可以传入函数:
def func(infile, some_other_data, outfile, function_from_status_variable):
with open(infile, 'r') as f:
with open(outfile, 'w') as outf:
for line in f:
# parse line
for element in some_other_data:
standard_function(line, element)
function_from_status_variable(line, element)
outf.write(new_line)
计算一次,因此:
def calc_function(status_variable):
if status_variable == 'status_A':
return function_A
elif status_variable == 'status_B':
return function_B
# other tests follow, plus handle an unknown value
最后像这样调用函数:
function = calc_function(status_variable)
func(infile, some_other_data, outfile, function)
添加回答
举报
