CodingNic

Object-Oriented Programming

Creating Multiple Objects

Object-Oriented Programming 28 min read

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

python
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

text
Tom 85
Sara 92
Ali 70

Each Object Is Separate

Changing one object does not change others.

python
tom.score = 90

print(tom.score)
print(sara.score)

Output

text
90
92

Store Objects in a List

You can store objects inside a list.

python
students = [
    Student("Tom", 85),
    Student("Sara", 92),
    Student("Ali", 70)
]

for student in students:
    print(student.name, student.score)

Output

text
Tom 85
Sara 92
Ali 70

Example: Products

python
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:

text
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

  1. Can one class create many objects?
  2. Does changing one object change all objects?
  3. Can objects be stored in a list?
  4. 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.