2017-07-18 61 views
1

我有一个python脚本与一个通用的方法调用文件中的每一行功能。此方法将该函数作为此函数的参数和参数(可选)进行调用。问题是它将调用的某些函数需要参数,而其他函数则不需要。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

为什么?这完成哪些只是单独处理它们不会? – TemporalWolf

+0

究竟是什么问题?零参数是传递给一个带有* args的函数的有效事物,并且可以将一个空的*参数传递给一个采用零参数的函数。 – jasonharper

+0

为什么不只是调用两次'generic_method':一次为字符的另一个字符? – mquantin

回答

0

不会的,如果,否则满足您的需求?像这样:

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

这没有必要(至少在Py2.7中)。你可以简单地传递一个空的'* args',它并不介意。另外,它应该是函数调用的'* args'。 – TemporalWolf

+0

好的,我编辑过,谢谢:) – ImSoFancy

0

您还可以通过空*参数传递给这并不需要它们的功能...
如果一个函数只调用另一个函数,那么你可以绕过它,不是吗?

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)