Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of objects?

How do I go about creating a list of objects (class instances) in Python?

Or is this a result of bad design? I need this cause I have different objects and I need to handle them at a later stage, so I would just keep on adding them to a list and call them later.

like image 700
user225312 Avatar asked Jul 05 '10 21:07

user225312


People also ask

Can you have a list of objects in Java?

Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.


Video Answer


2 Answers

Storing a list of object instances is very simple

class MyClass(object):     def __init__(self, number):         self.number = number  my_objects = []  for i in range(100):     my_objects.append(MyClass(i))  # later  for obj in my_objects:     print obj.number 
like image 110
yanjost Avatar answered Sep 17 '22 12:09

yanjost


You can create a list of objects in one line using a list comprehension.

class MyClass(object): pass  objs = [MyClass() for i in range(10)]  print(objs) 
like image 36
cryptoplex Avatar answered Sep 21 '22 12:09

cryptoplex