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
.
1 2 3 4 5 6 7 |
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name}, {self.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:
1 2 3 |
person1 = Person("Alice", 30) person2 = Person("Bob", 25) person3 = Person("Eve", 35) |
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:
1 |
people = [person1, person2, person3] |
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:
1 2 |
for person in people: print(person) |
This will output the following:
Alice, 30 Bob, 25 Eve, 35
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f'{self.name}, {self.age}' person1 = Person("Alice", 30) person2 = Person("Bob", 25) person3 = Person("Eve", 35) people = [person1, person2, person3] for person in people: print(person) |
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.