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

调用带有参数的函数的python函数,python,Python,我有一个python脚本,它带有一个通用方法,可以为文件中的每一行调用函数。此方法将要调用的函数作为此函数的参数和参数(可选)。问题是,它将调用的某些函数需要参数,而其他函数则不需要参数 我该怎么做呢 代码示例: def check_if_invalid_characters(line, *args): # process word def clean_words_with_invalid_characters(): generic_method(check_if_invali

我有一个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()

如果,否则不能满足你的需求吗?像这样:

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

您仍然可以将空*参数传递给不需要它们的函数…
如果一个函数只调用另一个函数,那么你可以绕过它,不是吗

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)

您仍然可以将空*参数传递给不需要它们的函数…
如果一个函数只调用另一个函数,那么你可以绕过它,不是吗

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)

为什么?这能实现什么,而仅仅单独处理它们是不可能的?问题到底是什么?零参数传递给接受*args的函数是有效的,您可以将空*args传递给接受零参数的函数。为什么不调用两次
generic_方法呢?
:一次用于字符,另一次用于行?@jasonharper您是对的。我以为我以前测试过这个选项,结果出错了,但显然我错了。非常感谢。为什么?这能实现什么,而仅仅单独处理它们是不可能的?问题到底是什么?零参数传递给接受*args的函数是有效的,您可以将空*args传递给接受零参数的函数。为什么不调用两次
generic_方法呢?
:一次用于字符,另一次用于行?@jasonharper您是对的。我以为我以前测试过这个选项,结果出错了,但显然我错了。非常感谢。这是不必要的(至少在Py2.7中是这样)。您只需传递一个空的
*args
,它就不介意了。另外,函数调用应该是
*args
,这不是必需的(至少在Py2.7中是这样)。您只需传递一个空的
*args
,它就不介意了。此外,函数调用应该是
*args