How to create multiple class objects with a loop in python?
This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.
In this case, why not make a list of objs?
objs = [MyClass() for i in range(10)]
for obj in objs:
other_object.add(obj)
objs[0].do_sth()
Creating a dictionary as it has mentioned, but in this case each key has the name of the object name that you want to create. Then the value is set as the class you want to instantiate, see for example:
class MyClass:
def __init__(self, name):
self.name = name
self.checkme = 'awesome {}'.format(self.name)
...
instanceNames = ['red', 'green', 'blue']
# Here you use the dictionary
holder = {name: MyClass(name=name) for name in instanceNames}
Then you just call the holder key and you will have all the properties and methods of your class available for you.
holder['red'].checkme
output:
'awesome red'
you can use list to define it.
objs = list()
for i in range(10):
objs.append(MyClass())