How to create a list of objects?

Question:

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.

Asked By: user225312

||

Answers:

The Python Tutorial discusses how to use lists.

Storing a list of classes is no different than storing any other objects.

def MyClass(object):
    pass

my_types = [str, int, float, MyClass]
Answered By: Chris B.

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
Answered By: yanjost

I think what you’re of doing here is using a structure containing your class instances. I don’t know the syntax for naming structures in python, but in perl I could create a structure obj.id[x] where x is an incremented integer. Then, I could just refer back to the specific class instance I needed by referencing the struct numerically. Is this anything in the direction of what you’re trying to do?

Answered By: Andy

In Python, the name of the class refers to the class instance. Consider:

class A: pass
class B: pass
class C: pass

lst = [A, B, C]

# instantiate second class
b_instance = lst[1]()
print b_instance

if my_list is the list that you want to store your objects in it and my_object is your object wanted to be stored, use this structure:

my_list.append(my_object)
Answered By: Kooranifar

I have some hacky answers that are likely to be terrible… but I have very little experience at this point.

a way:

class myClass():
    myInstances = []
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02
        self.__class__.myInstances.append(self)

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

for thisObj in myClass.myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

A hack way to get this done:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar",  "Baz")

myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
    thisStep += 1
    if "myClass object at" in thisLocalsLine:
        print(thisLocalsLine)
        print(myLocals[(thisStep - 2)])
        #myInstances.append(myLocals[(thisStep - 2)])
        print(myInstances)
        myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)

Another more ‘clever’ hack:

import sys
class myClass():
    def __init__(self, myStr01, myStr02):
        self.myStr01 = myStr01
        self.myStr02 = myStr02

myInstances = []
myClasses = {
    "myObj01": ["Foo", "Bar"],
    "myObj02": ["FooBar",  "Baz"]
    }

for thisClass in myClasses.keys():
    exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
    myInstances.append(getattr(sys.modules[__name__], thisClass))

for thisObj in myInstances:
    print(thisObj.myStr01)
    print(thisObj.myStr02)
Answered By: Art Hill

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)
Answered By: cryptoplex

we have class for students and we want make list of students that each item of list is kind of student

class student :
    def __init__(self,name,major):
        self.name=name
        self.major=major


students = []
count=int(input("enter number of students :"))
#Quantify
for i in range (0,count):
    n=input("please enter name :")
    m=input("please enter major :")
    students.append(student(n,m))
#access
for i in students:
    print (i.name,i.major)
Answered By: Rezee.em
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.