简体   繁体   中英

Dynamically creating instances of a class using list of strings as variable names for instances

Lets say I want to produce multiple instances of a class (eg 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM