Reputation: 517
For example, say I have a list:
people = ["bob", "tom", "joe"]
I'd like to make a class instance for each name.
I'm guessing there's no easy way to create variable names on the fly, like so:
for num in range(0, 3):
person_"num" = Person(people[num])
How do I accomplish this?
Upvotes: 0
Views: 69
Reputation: 21163
As recommended in the comments using a dictionary is good for this:
people = ["bob", "tom", "joe"]
person_lookup = {}
for p in people:
person_lookup[p] = Person(p)
or more idiomatically:
people = ["bob", "tom", "joe"]
person_lookup = {p: Person(p) for p in people}
then use like:
person_lookup["bob"].some_method_on_person()
Upvotes: 2
Reputation: 14313
You can use exec
to accomplish your goal.
for num in range(0, 3):
exec("person_"+str(num)+" = Person(people[num])")
Upvotes: 1
Reputation: 131
Why not use a list of Person
s instead?
persons = []
people = [ "bob", "tom", "joe" ]
for p in people:
persons.append(Person(p))
Then you can index them by number.
Upvotes: 0