Creating a variable number of class instances
class, copy, python, python-3.x
Solution
You don't need to copy a class to make multiple instances of that class.
items = []
for i in range(10):
items.append(myClass())
`items` now contains ten separate `myClass` instances. You can access them individually with indexing, ex. `items[3]`.
Problem
My Class: ``` class myClass: pass ``` I am looking to recreate this effect: ``` x = myClass() y = myClass() z = myClass() ``` within a for loop because the number of times I need to loop will be varied each time. Trying this: ``` x = 3 for i in range(x): cls = myClass() ``` doesn't work because on each iteration I recreate the class instance. My thinking is that on each loop I need to create a copy of the class and store that in a dict for referencing. So my questions are: - Is this the right approach? - How do I create a copy of a class? My attempts to create a class so far have been unsuccessful as the class isn't totally individual. ``` x = deepcopy(cls) ``` ``` CopyOfCls = type('CopyOfCls', cls.__bases__, dict(cls.__dict__)) ``` EDIT: Answerers revealed that I was actually looking at creating multiple class instances.