我有一个带有泛型方法的python脚本,该方法为文件中的每一行调用函数。此方法将函数作为参数和参数(可选)调用此函数。问题是它所调用的一些功能需要参数而其他功能不需要。
我将如何做到这一点?
代码示例:
def check_if_invalid_characters(line, *args):
# process word
def clean_words_with_invalid_characters():
generic_method(check_if_invalid_characters, *args)
def check_if_empty_line(line):
# process word
def clean_empty_lines():
generic_method(check_if_empty_line)
def generic_method(fun_name, *args):
with open("file.txt") as infile:
for line in infile:
if processing_method(line, *args):
update_temp_file(line)
clean_words_with_invalid_characters()
clean_empty_lines()
答案 0 :(得分:0)
不会是if,否则满足你的需求?像这样:
def whatever(function_to_call,*args):
if(len(arg)>0):
function_to_call(*args)
else:
function_to_call()
答案 1 :(得分:0)
您仍然可以将空* args传递给不需要它们的函数...
如果一个函数只调用另一个函数,那么你可以绕过它,不是吗?
def check_if_invalid_characters(line, *args):
# process word using *args
print(args)
def check_if_empty_line(line, *args):
print(args)
# process word and don't use *args (should be empty)
def generic_method(processing_method, *args):
with open("file.txt") as infile:
for line in infile:
if processing_method(line, *args):
update_temp_file(line)
generic_method(check_if_invalid_characters, foo, bar)
generic_method(check_if_empty_line)