Creating Multiple Objects
Creating Multiple Objects
One of the biggest strengths of OOP is this:
You can create many objects from one class.
Each object can store its own data.
Why This Matters
Real programs need many items.
Examples:
- many users
- many products
- many students
- many cars
- many game enemies
Instead of writing separate code each time, use one class.
Review
A class is a blueprint.
Objects are real items created from that blueprint.
Example: Students
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
tom = Student("Tom", 85)
sara = Student("Sara", 92)
ali = Student("Ali", 70)
print(tom.name, tom.score)
print(sara.name, sara.score)
print(ali.name, ali.score)
Output
Tom 85
Sara 92
Ali 70
Each Object Is Separate
Changing one object does not change others.
tom.score = 90
print(tom.score)
print(sara.score)
Output
90
92
Store Objects in a List
You can store objects inside a list.
students = [
Student("Tom", 85),
Student("Sara", 92),
Student("Ali", 70)
]
for student in students:
print(student.name, student.score)
Output
Tom 85
Sara 92
Ali 70
Example: Products
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
book = Product("Book", 10)
pen = Product("Pen", 2)
print(book.name, book.price)
print(pen.name, pen.price)
Why This Is Powerful
You write the class once.
Then create as many objects as needed.
Code Along
Create a class called Car.
Use brand and color.
Create three car objects and print them.
Mini Challenge
Create a class called Phone.
Steps:
-
Use
__init__()with:- brand
- model
-
Create three phones
-
Store them in a list
-
Loop and print all phone details
Expected output:
Apple iPhone
Samsung Galaxy
Google Pixel
Real World Use Case
Stores create many product objects. Schools create many student objects. Games create many enemy objects.
Quiz
- Can one class create many objects?
- Does changing one object change all objects?
- Can objects be stored in a list?
- Why is this useful?
Assignment
Create a Book class. Make four book objects and print all titles.
Summary
You learned how one class can create many separate objects and how to manage them in lists.