我传递了大量数据;具体来说,我试图将函数的输出传递给一个类,输出包含一个带有三个变量的元组。我不能像输入参数那样直接将我的函数(元组)的输出传递给类。
如何格式化元组,使其在没有input_tuple[0], input_tuple[1], input_tuple[2]
的情况下被类接受?
这是一个简单的例子:
#!/usr/bin/python
class InputStuff(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
input_tuple = (1, 2, 3)
instance_1 = InputStuff(input_tuple)
# Traceback (most recent call last):
# File "Untitled 3.py", line 7, in <module>
# instance_1 = InputStuff(input_tuple)
# TypeError: __init__() takes exactly 4 arguments (2 given)
InputStuff(1, 2, 3)
# This works
答案 0 :(得分:3)
您可以使用*
运算符unpack the argument list:
input_tuple = (1,2,3)
instance_1 = InputStuff(*input_tuple)
答案 1 :(得分:2)
您正在寻找:
Unpacking Argument Lists
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]