首页 > 解决方案 > 在 Python 中传递多个不同的函数参数

问题描述

首先,我已经看到了许多类似的问题,尽管它们并不完全是我的问题。我已经很熟悉了*args 和 **kwargs。

问题解释:

我通常在调用函数时使用位置参数。但是,我经常发现自己需要将过多的参数传递给函数,因此使用位置参数变得相当繁琐。我还发现自己需要将不同数量的变量传递给一个可以在需要时接受更多或其他变量的函数。

如何将许多参数传递给能够接受不同数量参数的函数?

我试图创建一个尽可能基本的示例。这些函数只是对一些变量执行一些算术运算,然后将它们打印出来。

a = 10
b = 20
c = 30

def firstFunction(*args):
    d = a *2
    e = b /2
    f = c +2

    x = d -10
    y = e -10
    z = f -10

    h = 1 #or 2

    secondFunction(d,e,f,h)
    thirdFunction(x,y,z,h)

def secondFunction(d,e,f,h):
    if h == 1:
        print d
        print e
        print f

def thirdFunction(x,y,z,h):
    if h == 2:
        print x
        print y 
        print z

firstFunction(b,c,a)

正如预期的那样,对于 h=1 和 h=2 分别产生的结果是:

20
10
32

10
0
22

现在假设我想将第二个和第三个函数组合在一起,所以我只需要调用一个函数而不是两个。在这种情况下,函数将是:

def combinedFunction(d,e,f,h,x,y,z):
     if h == 1:
        print d
        print e
        print f

     if h == 2:
        print x
        print y 
        print z

并会被调用:combinedFunction(d,e,f,h,x,y,z)。可以想象,对于更复杂的功能,这可能会变得非常烦人。此外,我传递了许多根本不会使用的不同参数,并且必须首先声明它们中的每一个。例如,在示例中, if h = 1, x, yandz仍然必须传递给函数,并且其中一个的值可能尚未确定(在这个简单的情况下是这样)。我不能使用 'combinedFunction(*args)' 因为不是每个参数都是全局定义的。

TLDR:

基本上我想要以下内容:

def someFunction(accepts any number of arguments **and** in any order):
   # does some stuff using those arguments it received at the time it was called
# it can accept many more parameters if needed
# it won't need to do stuff to a variable that hasn't been passed through

这个函数被调用:

someFunction(sends any number of arguments **and** in any order)
# can call the function again using different arguments and a
# different number of arguments if needed

这很容易实现吗?

标签: python

解决方案


在函数内部使用全局变量通常是一种不好的方法。取而代之的是,您可以使用**kwargs这种方式:

def firstFunction(**kwargs):
    d = kwargs.get('a') * 2

    secondFunction(d=d, **kwargs)
    thirdFunction(e=1, **kwargs)

def secondFunction(d, **kwargs):
    print d
    print kwargs.get('a')

def thirdFunction(**kwargs):
    print kwargs.get('e')

firstFunction(a=1, b=3, q=42)  # q will not be used

推荐阅读