Search code examples
pythoninstance

creating multiple instances of a class in Python


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


Solution

  • 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')}