简体   繁体   English

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

[英]Way to pass multiple parameters to a function in python

I have written a python script which calls a function. 我编写了一个调用函数的python脚本。 This function takes 7 list as parameters inside the function, something like this: 此函数将7个列表作为函数内的参数,如下所示:

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

where all the arguments except link are lists. 其中除link之外的所有参数都是列表。 But this makes my code looks pretty ugly. 但这使得我的代码看起来很丑陋。 I pass these lists to this function because the function appends few values in all of these lists. 我将这些列表传递给此函数,因为该函数在所有这些列表中附加了几个值。 How can I do it in more readable way for other users? 如何以更易读的方式为其他用户执行此操作?

test function: 测试功能:

You can use multiple arguments representing by *args and multiple keywords representing by **kwargs and passing to a function: 您可以使用多个参数来表示*args和多个关键字,这些关键字由**kwargs表示并传递给函数:

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

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

Example: 例:

Then use any type of data as arguments and as many parameters as keywords for the function. 然后使用任何类型的数据作为参数,并使用与函数关键字一样多的参数。 The function will automatically detect them and separate them to arguments and keywords: 该函数将自动检测它们并将它们分离为参数和关键字:

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)

Output: 输出:

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

keywords are:
param3
param2
param1

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 details转换为字典会更加健壮,将变量名称作为键,因此请在几行代码与防御性编程之间选择= p

You could use *args if you don't need to use names for your lists: 如果您不需要为列表使用名称,则可以使用*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)

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)

I think that usage of **kwarg is better. 我认为** kwarg的用法更好。 Look this example: 看这个例子:

def MyFunc(**kwargs):
    print kwargs


MyFunc(par1=[1],par2=[2],par3=[1,2,3])

Usually, passing more than 3 parameters to a function is not recommended. 通常,不建议将超过3个参数传递给函数。 This is not specific to python but to software design in general. 这不是python特有的,而是一般的软件设计。 You can read more about how to reduce the number of parameters passed to a function here . 您可以在此处阅读有关如何减少传递给函数的参数数量的更多信息。

Following the perspective of previous answers, but from a more general point of view I would like to add that there are several ways to make your code more readable: 按照以前的答案的观点,但从更一般的角度来看,我想补充一点,有几种方法可以使您的代码更具可读性:

  • to divide your function in simpler ones which have fewer arguments (define a function that takes your variable link , specific_list , list_type . By doing this you can detect within your WorkDetails function which list you passed with list_type and add the correct elements to that specific list ) 将函数划分为具有较少参数的较简单函数(定义一个带有变量link的函数, specific_listlist_type 。通过执行此操作,您可以在WorkDetails函数中检测使用list_type传递的列表,并将正确的元素添加到该specific list
  • to create a parameter object/data structure which is passed to your function (this is what previous answers suggested using lists , dictionaries ...) 创建一个传递给你的函数的参数对象/数据结构(这是以前的答案建议使用列表字典 ......)

Hope this help. 希望这有帮助。

That you need to pass that many lists is a sign that your function is not doing just one thing and you should refactor it by breaking it into smaller functions and/or converting it to a class. 您需要传递那么多列表,这表明您的函数不是只做一件事,您应该通过将其分解为更小的函数和/或将其转换为类来重构它。 You can pass parameters as keywords, or pass an arbitrary number of parameters to a function, as described by this StackOverflow page , but it'll still be hard for others to read and understand if you have your function do more than one thing. 您可以将参数作为关键字传递,或者将任意数量的参数传递给函数, 如此StackOverflow页面所述 ,但如果您的函数执行多项操作,则其他人仍然难以阅读和理解。

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

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