0

So I have a function that can take any number of lists as arguments. With each list, I want to initiate a class object. How do I unwrap the list so I can pass it straight in to the object creation?

list_of_routes = []

class Rope_route():
    def __init__(self, setter, color, grade):
        self.setter = setter
        self.color = color
        self.grade = grade


def set_route(*args)
    #each arg should be [setter, color, grade]
    for item in args
        list_of_routes.append(Rope_route(item))

set_route(['jimmy','green','v1'],['jonny','blue','v0'])

Is there a better way to solve this than by doing the following?

def __init__(self, args_as_list)
    self.setter = args_as_list[0]
    self.color = args_as_list[1]
    self.grade = args_as_list[2]
JiMJAM
  • 3
  • 2
  • Related: https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters – David Z Aug 18 '18 at 00:08

2 Answers2

1

You can expand a list as arguments using *, e.g.:

def set_route(*args):
    #each arg should be [setter, color, grade]
    return [Rope_route(*item) for item in args]


list_of_routes = set_route(...)

Note: it is better to return a value rather than modify a global variable.

AChampion
  • 29,683
  • 4
  • 59
  • 75
0

How about:

def __init__(self, args_as_list):
    self.setter, self.color, self.grade = args_as_list
Reza Dodge
  • 174
  • 1
  • 2
  • 4