2

I would like to create several instances of a Class, I tried to make a for loop to name them differently. Something like this, which doesn't work because the instance name is not supposed to be a string:

class A:
    pass

for i in range(10):
    "a"+str(i) = A()

Here the result I expect is 10 instances of the class A named: a0, a1, ... , a9.

How should I do?

2 Answers2

2

You can use dictionaries,

classes = {}
for i in range(10):
    classes[f"a{i}"]  = A()

Then you can access the class instance like this classes["a7"].

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
0

i can think in two ways. The trash way and a good way

Thrash:

class A:
    pass

for i in range(10):
    eval("a"+str(i)) = A()

Good:

class A:
    pass

a= []
for i in range(10):
    a[i] = A()
Jasar Orion
  • 626
  • 7
  • 26