How To Print All Objects In A Python Class

In this tutorial, we will learn how to print all objects in a class in Python. This could be helpful when you want to list all the instances of a class for further processing or to display the results interactively.

Step 1: Create a Class

First, let’s create a simple class Person with two attributes: name and age.

This class can be used to create and store information about different people. The __str__ method allows us to return a formatted string for each instance when we print it.

Step 2: Create Instances of the Class

Now, let’s create some instances of our Person class:

Step 3: Store Instances in a Collection

We need to keep track of all instances of our class to print them later. We will use a list to store our Person objects:

Step 4: Print All Objects in the Class

Now that we have our instances stored in a list, we can iterate through the list and print each object:

This will output the following:

Alice, 30
Bob, 25
Eve, 35

Full Code

Conclusion

In this tutorial, we learned how to print all objects in a class in Python by creating a class, creating instances of the class, storing instances in a collection, and then iterating and printing each object. This technique can be applied to any Python class and allows us to access and display all instances of that class.