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()
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With