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
x
17
17
1
class Worker(object):
2
3
4
def __init__(self, name, age):
5
self.name=name
6
self.age=age
7
8
worker_list=["w1", "w2", "w3"]
9
10
for i in worker_list:
11
name=input("what is the worker's name?")
12
age=input("What is the worker's age?")
13
i=Worker(name, age)
14
15
print(w1.name)
16
17
Advertisement
Answer
JavaScript
1
17
17
1
class Worker(object):
2
def __init__(self, name, age):
3
self.name=name
4
self.age=age
5
6
worker_list=["w1", "w2", "w3"]
7
8
workers = {}
9
10
for worker in worker_list:
11
name=input("what is the worker's name?")
12
age=input("What is the worker's age?")
13
object=Worker(name, age)
14
workers[worker] = object
15
16
print(workers['w1'].name)
17
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.