【问题标题】:How to make a function that parses variable parameters?如何制作解析可变参数的函数?
【发布时间】:2019-08-14 16:37:34
【问题描述】:

我正在尝试制作一个方法列表和一个参数列表,并找到所有不会引发错误的可能匹配项,但我无法找到一种方法来制作一个可以自动输入任何数字的函数参数的数量取决于功能的要求。

下面的代码是我得到的最接近的。我已经研究过 *args 和 **kwargs 之类的东西,但我需要它在函数调用而不是函数中进行缩放。 我对函数的包装器做了一些工作,但找不到 100% 自动化的解决方案。

    for f in self.functions:  # loop all functions
        for c in self.conditions:  # loop all conditions

            try:  # tries combination
                f(c)

            except TypeError as e: 

                for c2 in self.conditions:  

                    try: 
                        f(c, c2)

                    except TypeError as a:  

@staticmethod def test_method1(x): print("test_method1 = "+str(x))

@staticmethod
def test_method2(x, y):
    print("test_method2 = " + str(x)+" : "+str(y))

我想要一个可以给 f() 任意数量的参数的方法,以便相同的方法能够处理:

def test_method1(x):

def test_method2(x, y):

def test_method2(x, y, z):

等等。

我还需要能够将函数和给定参数保存在一个对象中,例如:

function = f
given_succesful_conditions = []

【问题讨论】:

  • 请正确格式化您的代码。

标签: python generics typeerror


【解决方案1】:

正确的做法是使用*args。从字面上看,它旨在处理您不知道传入多少参数的情况。

当您不确定可以将多少个参数传递给您的函数时,您可以使用 *args,即它允许您将任意数量的参数传递给您的函数。 source

例子:

def test_method(*args):
    print(args)

test_method('x')
('x',)

test_method('x','y','z')
('x', 'y', 'z')

在文档中,它被称为4.7.3. Arbitrary Argument Lists

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2020-10-25
    • 1970-01-01
    • 2014-09-12
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多