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.

   class Worker(object):
        
    
        def __init__(self, name, age):
             self.name=name
             self.age=age
    
    worker_list=["w1", "w2", "w3"]
    
    for i in worker_list:
        name=input("what is the worker's name?")
        age=input("What is the worker's age?")
        i=Worker(name, age)
        
    print(w1.name)
            

Advertisement

Answer

class Worker(object):
    def __init__(self, name, age):
        self.name=name
        self.age=age

worker_list=["w1", "w2", "w3"]

workers = {}

for worker in worker_list:
    name=input("what is the worker's name?")
    age=input("What is the worker's age?")
    object=Worker(name, age)
    workers[worker] = object

print(workers['w1'].name)

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