How to create a list of objects in the Python class


Python is a dynamic and skilled programming language that supports object−oriented programming (OOP). At the heart of OOP is the concept of objects, which are instances of a class. Classes in Python serve as blueprints for creating objects with specific attributes and methods. One common use case in OOP is to create a list of objects, where each object represents a unique instance of the class.

In this article, we will talk about the process of creating a list of objects within a Python class. We will discuss the essential steps involved, including defining a class, creating objects of that class, adding them to a list, and performing various operations on the objects in the list. To provide a clear understanding, we will also present examples and outputs to illustrate the concepts discussed. So, let's dive in and explore the world of creating lists of objects in Python classes!

Creating a Class in Python

In short, a class in Python is a blueprint or template for creating objects, defining their properties (attributes) and behaviors (methods). We use the class keyword followed by the class name and define attributes and methods inside the class block.

Here's an example of creating a class in Python:

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

In the above example, we outline a Python class referred to as "Student" with a special constructor method called "init". The constructor is mechanically called while an item of elegance is created by the use of the elegance call followed by parentheses. The "init" method takes three parameters − "call", "age", and "grade" − which are used to initialize the attributes of the item using the "self" keyword.

Creating Objects of the Class

Creating Objects of the Class in Python involves instantiating or creating instances of a class. A class serves as a blueprint or template for objects with specific attributes and behaviors. After defining a class, you can create multiple objects or instances of that class, each with its own unique set of attribute values.

Example

Here's an example of how to create objects or instances of a class:

# Create objects of the Student class
student1 = Student("Alice", 18, "A")
student2 = Student("Bob", 17, "B")
student3 = Student("Charlie", 19, "A+")

# Access and print attributes of the objects
print("Student 1:")
print("Name:", student1.name)
print("Age:", student1.age)
print("Grade:", student1.grade)

print("Student 2:")
print("Name:", student2.name)
print("Age:", student2.age)
print("Grade:", student2.grade)

print("Student 3:")
print("Name:", student3.name)
print("Age:", student3.age)
print("Grade:", student3.grade)

Output

Student 1:
Name: Alice
Age: 18
Grade: A
Student 2:
Name: Bob
Age: 17
Grade: B
Student 3:
Name: Charlie
Age: 19
Grade: A+

In the example, we instantiate three objects of the "Student" class − student1, student2, and student3 − each with unique attribute values for name, age, and grade. We then use dot notation to access and print the attribute values of each object. This illustrates the process of creating objects of a class and retrieving their attribute values to obtain the desired output.

Creating a List of Objects in the Class

Creating a list of objects within a class is a useful feature in Python that allows you to store and manage multiple instances or values of a class. This can be helpful when dealing with objects that share similar characteristics or belong to the same category. Let's explore how to create a list of objects in a class using an example to better understand the concept.

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade
        self.students_list = []  # Initialize an empty list to store student objects

    def add_student(self, student):
        self.students_list.append(student)  # Append student objects to the list

# Create student objects
student1 = Student("Alice", 18, "A")
student2 = Student("Bob", 17, "B")
student3 = Student("Charlie", 19, "A+")

# Add student objects to the list
student1.add_student(student1)
student1.add_student(student2)
student1.add_student(student3)

# Access objects in the list
print(student1.students_list) 

Output

[<__main__.Student object at 0x7f8c87e35e80>, <__main__.Student object at 0x7f8c87e35ef0>, <__main__.Student object at 0x7f8c87e35f60>]

The output is a list of student objects appended to the 'students_list' attribute of the 'student1' object. Each object is represented as <main.Student object at 0x7f8c87e35exx>, where 'xx' is a hexadecimal number denoting the memory address of the object. Please note that the memory addresses may vary upon each execution of the code, as they depend on the system's memory allocation.

Accessing Objects in the List

After adding student objects to the "students_list", we can easily access them using standard list indexing or iteration. Let's take a look at an example to see how we can access the objects in the list.

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade
        self.students_list = []

    def add_student(self, student):
        self.students_list.append(student)

    def get_students(self):
        return self.students_list

# Create student objects
student1 = Student("Alice", 18, "A")
student2 = Student("Bob", 17, "B")
student3 = Student("Charlie", 19, "A+")

# Add student objects to the list
student1.add_student(student1)
student1.add_student(student2)
student1.add_student(student3)

# Access objects in the list
students_list = student1.get_students()  # Get the list of student objects
# Access objects using list indexing
print(students_list[0].name)  
print(students_list[1].name)
print(students_list[2].name) 

Output

Alice
Bob
Charlie

In the output, you can see that the names of all the students are printed by using list index numbers. The dot notation is then used to access the "name" attribute of each student object, allowing us to obtain the names of the students.

Conclusion

In summary, utilizing a list of objects in a Python class is a valuable technique for effectively storing and managing multiple instances of a class. It facilitates efficient storage, retrieval, and manipulation of objects, simplifying the execution of various operations on them. By incorporating a list attribute within the class and using class or instance methods to append objects to it, easy access, addition, removal, and modification of objects in the list becomes possible. This approach proves particularly advantageous in scenarios where there is a need to manage multiple instances of a class with similar properties or behaviors.

Updated on: 25-Jul-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements