Home > Net >  Creating class instances iteratively in loop
Creating class instances iteratively in loop

Time:04-15

I want to create multiple instances of a class using a for loop and giving them different names:

robot_list = []
for i in range(10):
    robot_list.append(robot   str(i) = BasicNavigator())

This doesn't work, and currently, I am doing this:

robot_list = []
robot0 = BasicNavigator()
robot_list.append(robot0)
robot1 = BasicNavigator()
robot_list.append(robot1)
robot2 = BasicNavigator()
robot_list.append(robot2)

But I would like to make it more dynamic, so I choose e.g. 7 robots, it creates 7 instances, you know?

Any way of doing this?

CodePudding user response:

As you want to store the instance alongside the name of that instance, using a dictionary is the best choice.

This can help you create the number of instances you want and store them inside a list.

class Robot():
  def talk(self):
    return "Hi, I am a robot"

robots_num = 7
robots = {}
for i in range(robots_num):
  robots[f"robot_{i}"] = Robot()

print(robots["robot_0"].talk())

Output-

Hi, I am a robot
  • Related