Arrays of Objects Example in Python

Here, we are going to learn about the array of objects in Python and going to explain it by writing Python program to take student information and store it into an array of objects and then print the result.
Submitted by Shivang Yadav, on February 15, 2021

Python objects

Python objects are the instances of class in Python. And storing multiple objects into an array is an array of objects.

Problem statement

We need to store details of multiple students in an array of objects. And then print the students' results.

Problem description

We will take the students' details, (roll number, name, marks in physics, chemistry and maths) from users for multiple students as required by users. And the print the result that displays student's roll number, name and percentage ( sum of all marks  / 300 * 100).

Algorithm

  • Step 1: Create a class named Student to store student information.
  • Step 2: Take inputs from the user, and store it into an array of objects using getStudentInfo() method.
  • Step 3: After the user has entered all student's information. Print the result.
  • Step 4: The result printed as roll number, name, and percentage using printResult() method.

Python program to illustrate arrays of Objects

class Student:
    def GetStudentInfo(self):
        self.__rollno = input("Enter Roll Number ")
        self.__name = input("Enter Name ")
        self.__physics = int(input("Enter Physics Marks "))
        self.__chemistry = int(input("Enter Chemistry Marks "))
        self.__maths = int(input("Enter Math Marks "))
    def printResult(self):
        print(self.__rollno,self.__name, ((int)( (self.__physics+self.__chemistry+self.__maths)/300*100 )))

StudentArray = []

while(True):
    student = Student()
    student.GetStudentInfo()
    StudentArray.append(student)
    ch = input("Add More y/n?")
    if(ch=='n'):break

print("Results : ")

for student in StudentArray:
    student.printResult()

Output

Enter Roll Number 001
Enter Name John
Enter Physics Marks 87
Enter Chemistry Marks 67
Enter Math Marks 90
Add More y/n?y
Enter Roll Number 002
Enter Name Jane
Enter Physics Marks 54
Enter Chemistry Marks 87
Enter Math Marks 98
Add More y/n?n
Results : 
001 John 81
002 Jane 79

Python class & object programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.