Pass multiple arguments in form of tuple [duplicate]

不羁的心 提交于 2019-12-29 08:19:11

问题


I'm passing a lot data around; specifically, I'm trying to pass the output of a function into a class and the output contains a tuple with three variables. I can't directly pass the output from my function (the tuple) into the class as in the input parameters.

How can format the tuple so it is accepted by the class without input_tuple[0], input_tuple[1], input_tuple[2]?

Here is a simple example:

#!/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

回答1:


You can use the * operator to unpack the argument list:

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



回答2:


You are looking for: 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]


来源:https://stackoverflow.com/questions/32896651/pass-multiple-arguments-in-form-of-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!