首页 > 解决方案 > 打包函数参数

问题描述

我想调用一个在单个变量中发送多个参数的函数。

换句话说,我想做Test(some_var)与示例中相同的结果x1

class Test:    
    def __init__(self, one, two=None):
        self.one = one

        if two is not None:
            self.two = two


tup = 'a', 'b'
lst = ['a', 'b']

x1 = Test('a', 'b')
x2 = Test(tup)
x3 = Test(lst)

标签: python

解决方案


您必须使用 operator 解压缩参数*

Test(*tup)

顺便说一句,*当您想按位置分配参数时,使用运算符。如果要按名称分配参数,可以将 operator **in 与字典一起使用:

def foo(a, b):
    print(a, b)

kwargs = {'b': 20, 'a': 0}

foo(**kwargs) # 0 20

推荐阅读