8

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

def WorkDetails(link, AllcurrValFound_bse, AllyearlyHLFound_bse, 
                AlldaysHLFound_bse, AllvolumeFound_bse, 
                AllprevCloseFound_bse, AllchangePercentFound_bse, 
                AllmarketCapFound_bse):

除了link列表之外的所有参数。但这使我的代码看起来很丑陋。我将这些列表传递给此函数,因为该函数在所有这些列表中附加了很少的值。对于其他用户,我怎样才能以更易读的方式做到这一点?

4

6 回答 6

13

测试功能:

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

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

    print('\nkeywords are:')
    for j in kwargs:
        print(j)

例子:

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

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)

输出:

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

keywords are:
param3
param2
param1
于 2017-08-03T07:04:35.783 回答
5

You can change it to:

def WorkDetails(link, details):

Then invoke it as:

details = [ AllcurrValFound_bse, AllyearlyHLFound_bse, 
            AlldaysHLFound_bse, AllvolumeFound_bse, 
            AllprevCloseFound_bse, AllchangePercentFound_bse, 
            AllmarketCapFound_bse ]
workDetails(link, details)

And you would get the different values out of details by:

AllcurrValFound_bse = details[0]
AllyearlyHLFound_bse = details[1]
...

It would be more robust to turn details into a dictionary, with the variable names as keys, so take your pick between a few more lines of code vs. defensive programming =p

于 2012-11-25T16:26:06.667 回答
2

You could use *args if you don't need to use names for your lists:

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)

Or you could use a dictionary

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)
于 2012-11-25T16:25:30.293 回答
1

我认为使用 **kwarg 更好。看这个例子:

def MyFunc(**kwargs):
    print kwargs


MyFunc(par1=[1],par2=[2],par3=[1,2,3])
于 2012-11-25T18:50:46.490 回答
0

您需要传递这么多列表表明您的函数不只做一件事,您应该通过将其分解为更小的函数和/或将其转换为类来重构它。您可以将参数作为关键字传递,或将任意数量的参数传递给函数,如StackOverflow 页面所述,但如果您的函数不止做一件事,其他人仍然难以阅读和理解。

于 2017-05-29T02:46:20.070 回答
0

通常,不建议向函数传递超过 3 个参数。这不是特定于 python,而是一般的软件设计。您可以在此处阅读有关如何减少传递给函数的参数数量的更多信息。

遵循先前答案的观点,但从更一般的角度来看,我想补充一点,有几种方法可以使您的代码更具可读性:

  • 将您的函数划分为具有较少参数的更简单的函数(定义一个接受变量的函数link, specific_list, list_type。通过这样做,您可以在WorkDetails函数中检测您传递的列表list_type并添加正确的元素specific list
  • 创建一个传递给您的函数的参数对象/数据结构(这是以前的答案建议使用列表字典...)

希望这有帮助。

于 2017-03-13T12:07:30.230 回答