Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple class objects with a loop in python?

Suppose you have to create 10 class objects in python, and do something with them, like:

obj_1 = MyClass() other_object.add(obj_1) obj_2 = MyClass() other_object.add(obj_2) . . . obj_10 = MyClass() other_object.add(obj_10) 

How would you do it with a loop, and assign a variable to each object (like obj_1), so that the code will be shorter? Each object should be accessible outside the loop

obj_1.do_sth() 
like image 721
alwbtc Avatar asked Feb 06 '14 09:02

alwbtc


People also ask

How do you make multiple objects at once in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.


1 Answers

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)] for obj in objs:     other_object.add(obj)  objs[0].do_sth() 
like image 140
RemcoGerlich Avatar answered Oct 01 '22 11:10

RemcoGerlich