[英]python function that calls functions some with parameters
I have a python script with a generic method that calls functions for every line in a file. 我有一个带有通用方法的python脚本,该方法为文件中的每一行调用函数。 This method takes the function to be called as a parameter and arguments (optional) for this function. 此方法将要调用的函数作为该函数的参数和参数(可选)。 The problem is that some of the functions that it will call need parameters and others don't. 问题在于它将调用的某些功能需要参数,而其他则不需要。
How would I go about doing this? 我将如何去做呢?
Code example: 代码示例:
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()
wouldn't an if ,else satisfy your needs? 如果不能,还满足您的需求吗? like this : 像这样 :
def whatever(function_to_call,*args):
if(len(arg)>0):
function_to_call(*args)
else:
function_to_call()
You can still pass empty *args to the function that doesn't need them... 您仍然可以将空* args传递给不需要它们的函数...
If a function only calls another function then you can bypass it, don't you? 如果一个函数仅调用另一个函数,那么您可以绕过它,不是吗?
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.