Jeroen
Jeroen

Reputation: 129

How can I make a list of instance names that can then be made into a class instance

so for example:

class Recipe:
    def __init__(self, *args):
    #does something with args

list = [schnitzel, goulash]  #list of instance names 
datalist =[[['chicken',2],['breadcrumbs', 100],['flour', 100]],[['beef', 500],['paprika powder', 100]]  #these are the args which are in the same index as as its name in list.

for i in list:
    i = Recipe(datalist[list.index(i)]) 

Now from this I want goulash and schnitzel to become an instance. However, the problem is that goulash and schnitzel are both undefined variables so it fails when I try to make list. I tried making the names into strings:

list =  ['schnitzel', 'goulash']

but it still doesn't work out.

Any idea how I could do this? Thanks!

Upvotes: 0

Views: 33

Answers (2)

Danil Speransky
Danil Speransky

Reputation: 30453

Use * operator to unpack arguments:

Recipe(*datalist[list.index(i)]) 

You also may want to pass the name to the initializer. Here is my suggestion (after refactoring):

class Recipe:
    def __init__(self, name, *args):
        print(name, args)

dishes = ['schnitzel', 'goulash']
ingridients = [[['chicken', 2], ['breadcrumbs', 100], ['flour', 100]], [['beef', 500], ['paprika powder', 100]]]
recipes = [Recipe(name, *args) for name, args in zip(dishes, ingridients)]

Upvotes: 0

TerryA
TerryA

Reputation: 59974

There are two solutions here, the first of which I probably recommend.

I think you might want to change the structure of your class to add some sort of id, so that you may be able to differentiate.

class Recipe:
    def __init__(self, name, *args):
        self.name = name
        #does something with args

Then change your list into a list of strings: lst = ['schnitzel', 'goulash'].

Now iterate through your list and create objects with each food name:

list_of_foods = []
for food, ingredients in zip(lst, datalist):
    list_of_foods.append(Recipe(food, *ingredients))

Note that I do *ingredients to unpack the contents of the ingredients into args. That way, if I did args[0] I'd get ('chicken', 2).

Now you have a list of your objects:

for food_obj in list_of_foods:
    print(food_obj.name) # This will print "schnitzel" then "goulash"

The second method is using dictionaries. Change the structure of your data list like so:

datalist = {"schnitzel":[['chicken',2],['breadcrumbs', 100],['flour', 100]],
"goulash":[['beef', 500],['paprika powder', 100]]}

Then you can do:

list_of_foods = []
for k, v in datalist.items():
    list_of_foods.append(Recipe(*v))

But then you're left with a list of foods with just objects and there's no way to differentiate what food is what. You could do list_of_foods.append([k, Recipe(*v)]), but I think this would be a little messy. That's why I implemented a Recipe.name attribute.


Good tip: Don't name a list list, it will override the built-in type.

Upvotes: 1

Related Questions