0

I am trying to iterate through a list of string and make each element an instance of an object. I made a simplified version just to demonstrate my issue. When I run this code, I get an error saying that 'David' is not defined. I understand what I have done wrong: when I wrote 'People[i] = Person()', People[i] became the variable name instead of calling each element from the list.

How do I call each element on a list and make it a variable, so that in this case, when I print(David.name), it would print 'David'?

class Person:
    def __init__(self):
        self.name = "Unassigned"



People = ["David", "Emma", "Brian"]

for i in range(len(People)):
    People[i] = Person()
 
print(David.name)
jbae42
  • 17
  • 1
  • 3
  • I've tried using placeholders like { }.format() or '%s' % but did not work – jbae42 Aug 22 '20 at 03:34
  • 3
    don't try to dynamically create variables like this, it is the *wrong way to do this*. Instead, use a *container*. A list works. If you want to map strings to a person, use a `dict` – juanpa.arrivillaga Aug 22 '20 at 03:37

3 Answers3

0

Here is a tweak for the above snippet you can try,

class Person:
    # init constructor
    def __init__(self, name):
        self.name = name

People = ["David", "Emma", "Brian"]

# instead of creating dynamic variable use a dict
peoples = {}

for p in People:
    # init object with person name
    peoples[p] = Person(p)
 
# access based on person name
print(peoples['David'].name)
sushanth
  • 8,275
  • 3
  • 17
  • 28
0

You want to dynamically create variables, which is not a good idea. The way you can do it is like so:

people = ["David", "Emma", "Brian"]

code = "class {name}:\n    pass\n{name}.name = '{name}'"
for name in people:
    exec(code.format(name = name), globals())

print(David.name)
#prints:
#'David'
Elan-R
  • 484
  • 3
  • 6
0

DO NOT assign variable names like that or mess with globals. Use dictionaries instead:

class Person:
    def __init__(self):
        self.name = 'Unassigned'

People = ["David", "Emma", "Brian"]

#create a list of your objects
obj_list = [Person() for i in range(len(People))]
#convert People names to dictionary keys
dictionary = dict(zip(People, obj_list))

print(dictionary['David'].name)
#Unassigned
Ehsan
  • 12,072
  • 2
  • 20
  • 33