2

so let's say there is a class A

and I can create instances of class A as follow

inst1 = A()

inst2 = A()

inst3 = A()
...

Can I do this job more neatly?

I have to create the instances as many as a certain number that is given by a server (the number can vary every time).

I'm expecting to do something like

for NUM in range(2):
    inst + NUM = A()

then the instances I want to get as a result would be three instances (inst0, inst1, inst2) that are class A.

Thank you in advance

2 Answers2

4

you can't create single variable if you don't assign them a specified name, for creating unknow amount of variables use lists (inndexed) or dictionarys (named):

Lists

with for loops:

instances = []

for x in range('number of instances'):

    instances.append(A())

with list comprehension (recommended):

instances = [A() for x in range('number of instances')]

Dictionarys

with for loops:

instances = {}

for x in range('number of instances'):

    instances['inst' + str(x)] = A()

with dict comprehension (recommended):

instances = {'inst' + str(x): A() for x in range('number of instances')}
Leonardo Scotti
  • 1,069
  • 8
  • 21
3

use a dictionary or list to create your variable

dictionary

d={}
for x in range(1, 10):
    d[f"inst{x}"] = A()

list

inst=[]
for i in range(10):
    inst.append(A())