繁体   English   中英

python函数调用一些带有参数的函数

[英]python function that calls functions some with parameters

我有一个带有通用方法的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()

如果不能,还满足您的需求吗? 像这样 :

def whatever(function_to_call,*args):
    if(len(arg)>0):
        function_to_call(*args)
    else:
        function_to_call()

您仍然可以将空* 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM