Reputation: 759
Lets say I want to produce multiple instances of a class (e.g. a Car
class).
I have the variable names I need to use in a list:
cars = ['Mustang', 'Camaro', 'Challenger']
How can I loop through the cars
list and create an instance of the Car
class with the variable name being the string within the cars
list.
Essentially doing the same as:
Mustang = Car()
Camaro = Car()
Challenger = Car()
I realise that dynamically creating variables is frowned upon, however I am using this to create instances of a class for each participant in a study, therefore I have their ID numbers in a list and want to use this ID number as the variable name for the class instance.
Upvotes: 0
Views: 49
Reputation: 810
Try this hope it helps: https://repl.it/OAQv
class Car:
pass
module_name = __import__('sys').modules[__name__]
setattr(module_name, 'Mustang', Car())
setattr(module_name, 'Camaro', Car())
setattr(module_name, 'Challenger', Car())
print(Mustang)
print(Camaro)
print(Challenger)
to dynamically create instance of class using list of strings
class Car:
pass
module_name = __import__('sys').modules[__name__]
cars = ['Mustang', 'Camaro', 'Challenger']
for car in cars:
setattr(module_name, car, Car())
print(Mustang)
print(Camaro)
print(Challenger)
Upvotes: 1