python - 以元组形式传递多个参数

标签 python class object arguments tuples

<分区>

我正在传递大量数据;具体来说,我试图将一个函数的输出传递给一个类,并且输出包含一个具有三个变量的元组。我不能像在输入参数中那样将函数(元组)的输出直接传递到类中。

如果没有 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

最佳答案

您可以使用 * 运算符来 unpack the argument list :

input_tuple = (1,2,3)
instance_1 = InputStuff(*input_tuple)

关于python - 以元组形式传递多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32896651/

相关文章:

python - 将一个K长度的列表拆分为尽可能 "even"的L个子列表,即使K/L留有余数

python - subprocess.Popen 无法正确管道 urllib3 响应

java - 在同一个类中声明一个类的对象时,内存无限

python - Pygame 矩形碰撞

c++ - 使用统一初始化初始化对象和指针对象不起作用

python - Django "Did you mean?"查询

python - 在 numpy 数组中找到第 k 个最小的元素

C++类——如何从另一个成员函数引用一个成员函数

javascript - 如何将集合添加到 Backbone 中的另一个集合

java - 设计: Use class or instance references?