Write a python program to Arrays of Objects


The Python program defines a Student class and creates a list (students) to store instances of the Student class. It also demonstrates how to access and modify attributes of a student. Here's a breakdown of the code:

  • class Student: This defines a class called Student, representing a student with attributes like roll_number, name, and marks.
  • __init__(self, roll_number, name, marks): The constructor method initializes a Student object with the provided roll_number, name, and marks.
  • __str__(self): This special method returns a string representation of the Student object, displaying the roll number, name, and marks.
  • students = []: This creates an empty list to store Student objects.
  • Three students are created and added to the students list using the append method. Each student has a unique roll number, name, and marks.
  • A for loop iterates over the list of students and prints the details of each student using the __str__ method.
  • It then demonstrates how to access and modify the attributes of a specific student. In this case, it selects the first student from the list, changes the name and marks, and prints the updated details.

Source Code

class Student:
    def __init__(self, roll_number, name, marks):
        self.roll_number = roll_number
        self.name = name
        self.marks = marks
 
    def __str__(self):
        return f"Roll Number : {self.roll_number}\nStudent Name : {self.name}\nMarks : {self.marks}"
 
students = [] # Create an array (list) of Student objects
 
students.append(Student(101, "Mithra", 85.5)) # Add students to the array
students.append(Student(102, "Akhil", 78.0))
students.append(Student(103, "Sathish", 92.5))
 
for student in students: # print individual student details
    print(student,"\n")
 
# Access and modify attributes of a student
student = students[0]
print("Before Update : ",student)
student.name = "Pooja"
student.marks = 90.0
print("\nAfter Update : ",student)

Output

Roll Number : 101
Student Name : Mithra
Marks : 85.5

Roll Number : 102
Student Name : Akhil
Marks : 78.0

Roll Number : 103
Student Name : Sathish
Marks : 92.5

Before Update :  Roll Number : 101
Student Name : Mithra
Marks : 85.5

After Update :  Roll Number : 101
Student Name : Pooja
Marks : 90.0

Example Programs