简体   繁体   English

如何在python中使用可选参数正确调用函数

[英]How to correctly call function with optional parameters in python

I'm a beginner with python and I'm facing a problem with a function that requires optional parameters. 我是python的初学者,并且遇到了需要可选参数的函数的问题。 This function gets as parameters a variable number of file paths, that can be from 2 to n parameters. 此函数以可变数量的文件路径作为参数,可以是2到n个参数。 After that, a certain number of optional parameters can be passed to this function. 之后,可以将一定数量的可选参数传递给该函数。 I tried to do something like that: 我试图做这样的事情:

def compareNfilesParameters(*args):
    start_time = time.time()

    listFiles = []
    listParameters = []

    for argument in args:
        if str(argument).endswith(".vcf"):
            listFiles.append(str(argument))
        else:
            listParameters.append(argument)

So if the parameters has the file extension it is considered as one of the file path parameters, the others are seen as the optional parameters. 因此,如果参数具有文件扩展名,则将其视为文件路径参数之一,将其他视为可选参数。

What I want to do is letting the user call the function like: 我想做的是让用户像这样调用函数:

function('a.vcf', 'b.vcf', 'c.vcf') 

or 要么

function('a.vcf', 'b.vcf', 'c.vcf', 0, 1)

or 要么

function('a.vcf', 'b.vcf', 'c.vcf', 0, 1, 4,...,3)

I tried different approaches but none of them satisfies me. 我尝试了不同的方法,但没有一个能让我满意。

The first approach is declaring the function as: 第一种方法是将函数声明为:

def compareNfilesParameters(*args)  

but this way, if I get for example 3 parameters, 2 will certainly be the files path, and the last one I don't know on which variable it refers. 但是这样,例如,如果我得到3个参数,则2个肯定是文件路径,而最后一个我不知道它所指向的变量。 So I need to specify every value and pass '-1' for the parameters that I want to use default value. 因此,我需要指定每个值,并为要使用默认值的参数传递“ -1”。

The 2nd approach is the following: 第二种方法如下:

def compareNfilesParameters(*args, par1 = 10, par2 = 15 ..)

But this way I need to call the function like: 但是这样,我需要像这样调用函数:

compareNfilesParameters(path1, path2, path3, par1 = 10)

and not like 而且不喜欢

compareNfilesParameters(path1, path2, path3, 10)

or the 10 will be considered in the args input, right? 还是在args输入中考虑10,对不对? I wouldn't like to use this approach because it becomes very verbose to call the function. 我不想使用这种方法,因为调用该函数变得非常冗长。

How would you do this? 你会怎么做?

Make the user pass in the filenames as a sequence; 让用户按顺序输入文件名; don't try to cram everything into separate arguments: 不要试图将所有内容塞入单独的参数中:

def compareNfilesParameters(files, *params):

and call this as: 并将其称为:

compareNfilesParameters(('a.vcf', 'b.vcf', 'c.vcf'), 0, 1, 4)

This makes the files explicit and removes the need to separate files from other parameters. 这样可以使文件显式显示,并且无需将文件与其他参数分开。

If your remaining parameters are distinct options (and not a homogenous series of integers), I'd use keyword arguments: 如果您其余的参数是不同的选项 (而不是同质的整数序列),则可以使用关键字参数:

def compareNfilesParameters(files, op1=default_value, op2=default_value, op3=default_value):

You don't have to use keyword arguments with keywords when calling; 调用时不必将关键字参数与关键字一起使用; you can still treat them as positional: 您仍然可以将它们视为位置:

compareNfilesParameters(('a.vcf', 'b.vcf', 'c.vcf'), 0, 1, 4)

would give op1 the value 0 , op2 the value 1 , and op3 the value 4 . 将为op1赋予0值, op2赋予1值, op3赋予4值。 Only if you want to specify values out of order or for a specific option do you have to use keyword arguments in the call: 仅当您要乱序指定值或为特定选项指定值时,才需要在调用中使用关键字参数:

compareNfilesParameters(('a.vcf', 'b.vcf', 'c.vcf'), op3=4)

Ok, I solved like using the keyword parameters as suggested. 好的,我像建议的那样使用关键字参数来解决。

def compareNfilesParameters(listFiles, **kwargs):
    start_time = time.time()

    if len(listFiles) < MINUMUM_FILES_NUMBER :
        print "You need to specify at least "+ str(MINUMUM_FILES_NUMBER) +" files."
        return

    try:
        operationType = int(kwargs.get("op", DEFAULT_OPERATION_TYPE))
    except ValueError:
        print "Operation type filter has to be an integer."
        return    
    if operationType not in [0,1]:
        print "Operation type must be 0 (intersection), 1 (union)"
        return

and so on for all the parameters. 等等所有参数。 Like this I need to put all the files paths in a list and pass it as a single required parameter, and searching kwargs dictionary for optionals parameters setting the default values if not expressed. 这样,我需要将所有文件路径放在一个列表中,并将其作为单个必需参数传递,并在kwargs词典中搜索可选参数,以设置未表达的默认值。

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

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