将多个参数传递给python中的函数的方法

Inv*_*tus 7 python parameters parameter-passing python-2.7

我已经编写了一个调用函数的python脚本。此函数将7列表作为函数内部的参数,如下所示:

def WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, 
                AlldaysHLFound_bse, AllvolumeFound_bse, 
                AllprevCloseFound_bse, AllchangePercentFound_bse, 
                AllmarketCapFound_bse):
Run Code Online (Sandbox Code Playgroud)

其中所有参数link均为列表。但这使我的代码看起来很难看。我将这些列表传递给该函数,因为该函数在所有这些列表中附加了几个值。我该如何以更具可读性的方式为其他用户使用?

ima*_*bet 7

测试功能:

您可以使用多个以*args和表示的参数,以及多个以**kwargs和传递给函数的关键字:

def test(*args, **kwargs):
    print('arguments are:')
    for i in args:
        print(i)

    print('\nkeywords are:')
    for j in kwargs:
        print(j)
Run Code Online (Sandbox Code Playgroud)

例:

然后,使用任何类型的数据作为参数,并使用与函数关键字一样多的参数。该函数将自动检测它们并将它们分隔为参数和关键字:

a1 = "Bob"      #string
a2 = [1,2,3]    #list
a3 = {'a': 222, #dictionary
      'b': 333,
      'c': 444}

test(a1, a2, a3, param1=True, param2=12, param3=None)
Run Code Online (Sandbox Code Playgroud)

输出:

arguments are:
Bob
[1, 2, 3]
{'a': 222, 'c': 444, 'b': 333}

keywords are:
param3
param2
param1
Run Code Online (Sandbox Code Playgroud)


sam*_*hen 5

您可以将其更改为:

def WorkDetails(link, details):
Run Code Online (Sandbox Code Playgroud)

然后将其调用为:

details = [ AllcurrValFound_bse, AllyearlyHLFound_bse, 
            AlldaysHLFound_bse, AllvolumeFound_bse, 
            AllprevCloseFound_bse, AllchangePercentFound_bse, 
            AllmarketCapFound_bse ]
workDetails(link, details)
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式从详细信息中获得不同的值:

AllcurrValFound_bse = details[0]
AllyearlyHLFound_bse = details[1]
...
Run Code Online (Sandbox Code Playgroud)

details将变量名作为键转换成字典会更健壮,因此在多行代码与防御性编程之间进行选择=p


小智 3

*args如果您不需要为列表使用名称,则可以使用:

def WorkDetails(link, *args):
    if args[0] == ... # Same as if AllcurrValFound_bse == ...
        ...

 # Call the function:
 WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, AlldaysHLFound_bse, AllvolumeFound_bse, AllprevCloseFound_bse, AllchangePercentFound_bse, AllmarketCapFound_bs)
Run Code Online (Sandbox Code Playgroud)

或者你可以使用字典

def WorkDetails(link, dict_of_lists):
    if dict_of_lists["AllcurrValFound_bse"] == ...
        ...

# Call the function
myLists = {
    "AllcurrValFound_bse": AllcurrValFound_bse,
    "AllyearlyHLFound_bse": AllyearlyHLFound_bse,
    ...,
    ...
}
WorkDetails(link, myLists)
Run Code Online (Sandbox Code Playgroud)