How to Count the Number of Objects in a Class in Python



Python


In this article, we show how to count the number of objects in a class in Python.

So, let's say we create a class called Student.

This class will contain Student objects, Student 1, Student 2, Student 3, Student 4, etc.

So it will contain a number of students, maybe representing a class of students.

While we're in the process of creating these Student objects (representing students), we may want to know how many Student objects we've created (which would represent the number of students in a class, for example).

So how can we do this in Python?

If we're creating a class in Python, you would want to create an __init__ method so that you can initialize what values get passed into each Student object, for example, the student's name, age, grade, etc.

The __init__ method in Python would be a constructor in other OOP languages.

The __init__ method is called every time an object of a class is created. Therefore, we put a simple incrementor in the __init__ method that counts up each time an object is created.

In our example code below, we create a class named Student and define an __init__ method. We then create Students objects. Lastly, we print out the number of Student objects that have been created.

We show all of this in the code below.



So let's now go through this code.

So, we create a class named Student.

We then create a class variable named number_of_students and initialize it to the value of 0.

We then create an __init__ method to determine what attributes must get passed to each new object of the Student class. In this case, it is name and grade.

Since the __init__ method is called every time a new object is created, we can take advantage of this fact to increment our class variable number_of_students in it. Since every new object created in the class must pass through the __init__ method, by incrementing the number_of_students variable by 1 each time, we can know how many objects are in the class.

Remember that number_of_students is a class variable. This means that to reference it we must use the statement, Student.number_of_students, not simply number_of_students (which will cause an UnboundLocalError).

We then create 5 Student objects.

We then print out the number of students in the class, which in this case is 5, since the number of objects we created is 5.

Thus, this is how we can count the number of objects in a class in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...