Ravindra BagaleCourses & study guides मराठी Track your progress

Python Classes and Objects for Beginners: OOP Basics with Simple Examples

P11.3 Many Objects in a List: Classes with Real Data

Why. Real data has many records. A list of objects lets you loop, filter and total them — like rows.

What. Create objects in a loop or a list, then use normal list tools on them.

How.

Work with many objects

  1. Create a list of objects.
  2. Loop over it.
  3. Read attributes or call methods.
  4. Total or filter as needed.

Worked example A — Patients in a ward.

Step 1 — What we do. A hospital in Chennai tracks patients and flags fever.

Step 2 — Type and run this code.

class Patient:
    def __init__(self, name, temp_f):
        self.name = name
        self.temp_f = temp_f

    def has_fever(self):
        return self.temp_f >= 100.4

ward = [Patient("Anil", 98.6), Patient("Fatima", 101.2), Patient("Grace", 100.4)]
for p in ward:
    if p.has_fever():
        print(p.name, "has fever")

Step 3 — Output you should see.

Fatima has fever
Grace has fever

Step 4 — What it means. Each object answers the same question with its own data.

Worked example B — Totals across objects.

Step 1 — What we do. Delivery vans and their loads for a logistics company in Rotterdam.

Step 2 — Type and run this code.

class Van:
    def __init__(self, van_id, parcels):
        self.van_id = van_id
        self.parcels = parcels

fleet = [Van("V1", 120), Van("V2", 95), Van("V3", 140)]
print(sum(v.parcels for v in fleet))
busiest = max(fleet, key=lambda v: v.parcels)
print(busiest.van_id)

Step 3 — Output you should see.

355
V3

Step 4 — What it means. Sums and max with key= work on objects too.

Ravindra Bagale's Tip

For data analysis, pandas is usually better than a list of objects. Use classes for tools and pipelines, not to store big tables.