Skip to content
Advertisement

Why can’t I initialize instances using for loop – Python, class

error: name ‘w1’ is not defined I tried to use for loop to initialize all the workers( w1, w2, w3) so i can access them afterwards. But when I try to access them they say the instance is not defined, is it possible that you cant initialize using for loop. Thanks in advance, beginner here.

JavaScript

Advertisement

Answer

JavaScript

I think the best solution is to use a dictionary, create a empty dictionary, and for any element in your worker_list insert a key/value pair into the dictionary, where the key is the element of your worker_list so, w1, w2, w3 and the value is the relative Worker() object.

This way you can retrieve your object using keys instead of anonymous numerical indeces.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement