Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 09 / Stage 2

Object-oriented Python

Goal: Model real things as classes and objects, and build small systems from them. Time: ~1 hour

What you will learn

  • Why OOP: keeping data and behaviour together
  • Classes, objects, __init__, self and instance attributes
  • Instance methods, class attributes, @classmethod and @staticmethod
  • Encapsulation: _protected, __private and @property
  • Inheritance: single, multilevel, super() and method overriding
  • Multiple inheritance and the MRO
  • Polymorphism and duck typing
  • Dunder methods: __str__, __repr__, __eq__, __lt__, __len__, __add__
  • Abstract classes with abc
  • @dataclass, Enum and StrEnum
  • Composition vs inheritance
  • A small bank account system that uses all of the above

Topics in this part

Practice

Python workbench — write and run code here

Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.

Write each answer in its own file. Put the demo calls in main() under if __name__ == "__main__": so the file runs on its own.


Exercise 1: Mobile phone class

Scenario: A mobile shop wants each phone on its price list to be an object. What to do:

  1. Write a class Phone with __init__(self, brand, model, price) that saves all three as instance attributes.
  2. Add a method label() that returns "<brand> <model>: ₹<price>" with a thousands comma.
  3. Add a method apply_discount(percent) that changes self.price to the discounted price, rounded to a whole rupee.
  4. Make the two phones below, give the first one 10% off, and print both labels.

Starting data:

first = Phone("Zentra", "Nova 5", 18999)
second = Phone("Kaveri", "Lite 2", 9499)

Sample output:

Zentra Nova 5: ₹17,099
Kaveri Lite 2: ₹9,499

💡 Hint: round(self.price * (100 - percent) / 100). Only first changes: each object has its own price.


Show the solution to Exercise 1
"""Exercise 1: Mobile phone class (__init__, self, instance methods).

Run:   python ex01.py   (macOS/Linux: python3 ex01.py)
"""


class Phone:
    def __init__(self, brand: str, model: str, price: int):
        self.brand = brand
        self.model = model
        self.price = price

    def label(self) -> str:
        return f"{self.brand} {self.model}: ₹{self.price:,}"

    def apply_discount(self, percent: int) -> None:
        self.price = round(self.price * (100 - percent) / 100)


def main() -> None:
    first = Phone("Zentra", "Nova 5", 18999)
    second = Phone("Kaveri", "Lite 2", 9499)
    first.apply_discount(10)
    print(first.label())
    print(second.label())


if __name__ == "__main__":
    main()

Exercise 2: Pizza orders

Scenario: A pizza counter has one menu for everyone and counts every order. What to do:

  1. Write a class Pizza with a class attribute PRICES = {"S": 149, "M": 249, "L": 399} and a class attribute orders = 0.
  2. __init__(self, name, size, qty=1) saves the values and adds 1 to Pizza.orders.
  3. A method total() returns price × quantity.
  4. A @classmethod from_string(cls, text) builds a pizza from text like "Paneer Tikka, L, 1".
  5. A @staticmethod is_valid_size(size) returns True only for a size in PRICES.
  6. Make Pizza("Margherita", "M", 2) and Pizza.from_string("Paneer Tikka, L, 1"), then print the lines below.

Sample output:

2 x Margherita (M) = ₹498
1 x Paneer Tikka (L) = ₹399
Orders: 2
Is XL a valid size? False

💡 Hint: In from_string, use text.split(","), .strip() each part, int() the quantity, then return cls(...).


Show the solution to Exercise 2
"""Exercise 2: Pizza orders (class attributes, @classmethod, @staticmethod).

Run:   python ex02.py   (macOS/Linux: python3 ex02.py)
"""


class Pizza:
    PRICES = {"S": 149, "M": 249, "L": 399}     # class attribute: shared menu
    orders = 0                                   # class attribute: counter

    def __init__(self, name: str, size: str, qty: int = 1):
        self.name = name
        self.size = size
        self.qty = qty
        Pizza.orders += 1

    def total(self) -> int:
        return Pizza.PRICES[self.size] * self.qty

    @classmethod
    def from_string(cls, text: str):
        name, size, qty = text.split(",")
        return cls(name.strip(), size.strip(), int(qty))

    @staticmethod
    def is_valid_size(size: str) -> bool:
        return size in Pizza.PRICES


def main() -> None:
    pizzas = [Pizza("Margherita", "M", 2), Pizza.from_string("Paneer Tikka, L, 1")]
    for pizza in pizzas:
        print(f"{pizza.qty} x {pizza.name} ({pizza.size}) = ₹{pizza.total()}")
    print("Orders:", Pizza.orders)
    print("Is XL a valid size?", Pizza.is_valid_size("XL"))


if __name__ == "__main__":
    main()

Exercise 3: Temperature with a property

Scenario: A weather app must never store a temperature below absolute zero (-273.15 °C). What to do:

  1. Write a class Temperature whose __init__(self, celsius) sets self.celsius = celsius.
  2. Make celsius a @property (stored in self._celsius) with a setter that raises ValueError(f"{value} °C is below absolute zero") for values below -273.15.
  3. Add a read-only property fahrenheit (no setter) that returns celsius * 9 / 5 + 32, rounded to 1 decimal.
  4. Make Temperature(41), print it, change it to 18.5, print again. Then try to set -300 and try to set fahrenheit = 100, catching each error.

Sample output:

41 °C = 105.8 °F
18.5 °C = 65.3 °F
Error: -300 °C is below absolute zero
Error: fahrenheit is read-only

💡 Hint: Setting a property that has no setter raises AttributeError. Catch it and print your own message.


Show the solution to Exercise 3
"""Exercise 3: Temperature (@property with a validating setter, read-only property).

Run:   python ex03.py   (macOS/Linux: python3 ex03.py)
"""

ABSOLUTE_ZERO = -273.15


class Temperature:
    def __init__(self, celsius: float):
        self.celsius = celsius                   # uses the setter

    @property
    def celsius(self) -> float:
        return self._celsius

    @celsius.setter
    def celsius(self, value: float) -> None:
        if value < ABSOLUTE_ZERO:
            raise ValueError(f"{value} °C is below absolute zero")
        self._celsius = value

    @property
    def fahrenheit(self) -> float:               # no setter: read-only
        return round(self._celsius * 9 / 5 + 32, 1)


def main() -> None:
    delhi = Temperature(41)
    print(f"{delhi.celsius} °C = {delhi.fahrenheit} °F")
    delhi.celsius = 18.5
    print(f"{delhi.celsius} °C = {delhi.fahrenheit} °F")
    try:
        delhi.celsius = -300
    except ValueError as e:
        print("Error:", e)
    try:
        delhi.fahrenheit = 100
    except AttributeError:
        print("Error: fahrenheit is read-only")


if __name__ == "__main__":
    main()

Exercise 4: Ride fares

Scenario: A ride app charges differently for a basic vehicle, an auto and a cab. What to do:

  1. Vehicle(number, rate_per_km) with fare(km) that returns round(rate_per_km * km).
  2. Auto(Vehicle) overrides fare so it is never below a class attribute MIN_FARE = 30. Use super().fare(km).
  3. Cab(Vehicle) has __init__(self, number, rate_per_km, ac=True) that calls super().__init__ and saves ac. Its fare adds ₹50 when ac is True.
  4. Loop over the rides below and print the class name (type(vehicle).__name__, padded to 8), the number, the km (right-aligned in 4) and the fare. Finally print the names of the classes in Cab.mro().

Starting data:

rides = [
    (Vehicle("KA01 1234", 10), 6),
    (Auto("KA02 5678", 15), 1.5),
    (Auto("KA02 5678", 15), 4),
    (Cab("KA03 9012", 20), 4),
    (Cab("KA04 3456", 20, ac=False), 4),
]

Sample output:

Vehicle  KA01 1234     6 km  ₹60
Auto     KA02 5678   1.5 km  ₹30
Auto     KA02 5678     4 km  ₹60
Cab      KA03 9012     4 km  ₹130
Cab      KA04 3456     4 km  ₹80
['Cab', 'Vehicle', 'object']

💡 Hint: One f-string does the row: f"{name:<8} {vehicle.number} {km:>4} km ₹{vehicle.fare(km)}". The loop never checks the type: that is polymorphism.


Show the solution to Exercise 4
"""Exercise 4: Ride fares (inheritance, super().__init__, overriding, polymorphism).

Run:   python ex04.py   (macOS/Linux: python3 ex04.py)
"""


class Vehicle:
    def __init__(self, number: str, rate_per_km: int):
        self.number = number
        self.rate_per_km = rate_per_km

    def fare(self, km: float) -> int:
        return round(self.rate_per_km * km)


class Auto(Vehicle):
    MIN_FARE = 30

    def fare(self, km: float) -> int:
        return max(super().fare(km), self.MIN_FARE)


class Cab(Vehicle):
    def __init__(self, number: str, rate_per_km: int, ac: bool = True):
        super().__init__(number, rate_per_km)
        self.ac = ac

    def fare(self, km: float) -> int:
        extra = 50 if self.ac else 0
        return super().fare(km) + extra


def main() -> None:
    rides = [
        (Vehicle("KA01 1234", 10), 6),
        (Auto("KA02 5678", 15), 1.5),
        (Auto("KA02 5678", 15), 4),
        (Cab("KA03 9012", 20), 4),
        (Cab("KA04 3456", 20, ac=False), 4),
    ]
    for vehicle, km in rides:
        name = type(vehicle).__name__
        print(f"{name:<8} {vehicle.number}  {km:>4} km  ₹{vehicle.fare(km)}")
    print([cls.__name__ for cls in Cab.mro()])


if __name__ == "__main__":
    main()

Exercise 5: Money with dunder methods

Scenario: A budget app wants to add, compare and sort amounts of money like numbers. What to do: Write a class Money with one attribute rupees and these methods:

  • __str__ → ₹15,000 · __repr__ → Money(15000)
  • __add__ → a new Money with the sum
  • __eq__ and __lt__ that compare rupees

Then, with the data below, print: rent + food, repr(travel), Money(500) == Money(500), the sorted list, the total, and the biggest expense.

Starting data:

rent = Money(15000)
food = Money(6500)
travel = Money(1800)
expenses = [rent, food, travel]

Sample output:

₹21,500
Money(1800)
True
[Money(1800), Money(6500), Money(15000)]
Total: ₹23,300
Biggest: ₹15,000

💡 Hint: sum() starts from the number 0, which cannot be added to a Money. Give it a start value: sum(expenses, Money(0)). max() works because of __lt__.


Show the solution to Exercise 5
"""Exercise 5: Money (dunder methods: __str__, __repr__, __add__, __eq__, __lt__).

Run:   python ex05.py   (macOS/Linux: python3 ex05.py)
"""


class Money:
    def __init__(self, rupees: int):
        self.rupees = rupees

    def __str__(self) -> str:
        return f"₹{self.rupees:,}"

    def __repr__(self) -> str:
        return f"Money({self.rupees})"

    def __add__(self, other):
        return Money(self.rupees + other.rupees)

    def __eq__(self, other) -> bool:
        return self.rupees == other.rupees

    def __lt__(self, other) -> bool:
        return self.rupees < other.rupees


def main() -> None:
    rent = Money(15000)
    food = Money(6500)
    travel = Money(1800)
    print(rent + food)
    print(repr(travel))
    print(Money(500) == Money(500))
    expenses = [rent, food, travel]
    print(sorted(expenses))
    print("Total:", sum(expenses, Money(0)))
    print("Biggest:", max(expenses))


if __name__ == "__main__":
    main()

Exercise 6: Notifications

Scenario: An online shop sends the same message by SMS, email and a chat bot. What to do:

  1. Write an abstract class Notifier(ABC) with an @abstractmethod send(self, to, message) that returns a string.
  2. SmsNotifier returns "SMS to <to>: " + the first 16 characters of the message + "...".
  3. EmailNotifier returns "Email to <to>: <message>".
  4. WhatsAppBot does not inherit from Notifier but has its own send that returns "WhatsApp to <to>: <message>".
  5. PushNotifier(Notifier) has only pass.
  6. Write notify_all(notifiers, to, message) that prints what each one returns. Call it with the first three for "Asha" and the message below. Then try PushNotifier() and print the TypeError.

Starting data:

message = "Your order #4521 is out for delivery"

Sample output:

SMS to Asha: Your order #4521...
Email to Asha: Your order #4521 is out for delivery
WhatsApp to Asha: Your order #4521 is out for delivery
TypeError: Can't instantiate abstract class PushNotifier without an implementation for abstract method 'send'

💡 Hint: notify_all works with WhatsAppBot because of duck typing: it only needs a send method. message[:16] gives the first 16 characters.


Show the solution to Exercise 6
"""Exercise 6: Notifications (abc.ABC, @abstractmethod, duck typing).

Run:   python ex06.py   (macOS/Linux: python3 ex06.py)
"""
from abc import ABC, abstractmethod


class Notifier(ABC):
    @abstractmethod
    def send(self, to: str, message: str) -> str:
        """Return a line describing what was sent."""


class SmsNotifier(Notifier):
    def send(self, to: str, message: str) -> str:
        return f"SMS to {to}: {message[:16]}..."    # SMS is kept short


class EmailNotifier(Notifier):
    def send(self, to: str, message: str) -> str:
        return f"Email to {to}: {message}"


class PushNotifier(Notifier):                    # forgot to write send()
    pass


class WhatsAppBot:                               # no parent, but it has send()
    def send(self, to: str, message: str) -> str:
        return f"WhatsApp to {to}: {message}"


def notify_all(notifiers, to: str, message: str) -> None:
    for notifier in notifiers:
        print(notifier.send(to, message))


def main() -> None:
    message = "Your order #4521 is out for delivery"
    notify_all([SmsNotifier(), EmailNotifier(), WhatsAppBot()], "Asha", message)
    try:
        PushNotifier()
    except TypeError as e:
        print("TypeError:", e)


if __name__ == "__main__":
    main()

Exercise 7: Task board

Scenario: A small team tracks its work on a board of tasks. What to do:

  1. Status(StrEnum) with TODO, DOING, DONE using auto().
  2. A @dataclass Task with fields title: str, priority: int (1 = most urgent), status: Status = Status.TODO and tags: list[str] (use field(default_factory=list)).
  3. A class TaskBoard that has a list of tasks (composition):
    • add(title, priority, *tags) makes a Task and adds it.
    • move(title, status) changes the status of the task with that title, or raises ValueError(f"No task called {title!r}").
    • count_by_status() returns a dict like {'todo': 1, 'doing': 1, 'done': 1}.
    • __len__ returns the number of tasks.
    • show() prints the board name with len(self), then each task sorted by priority (tags joined with ", ", or - when there are none).
  4. Run the steps below, then print count_by_status(), the third task (board.tasks[2]) and the error from move("Buy domain", Status.DONE).

Starting data:

board = TaskBoard("Website launch")
board.add("Write homepage", 2, "content")
board.add("Fix login bug", 1, "backend", "urgent")
board.add("Pick colours", 3)
board.move("Fix login bug", Status.DONE)
board.move("Write homepage", Status.DOING)
board.show()

Sample output:

Website launch (3 tasks)
  P1 Fix login bug    done   backend, urgent
  P2 Write homepage   doing  content
  P3 Pick colours     todo   -
{'todo': 1, 'doing': 1, 'done': 1}
Task(title='Pick colours', priority=3, status=<Status.TODO: 'todo'>, tags=[])
Error: No task called 'Buy domain'

💡 Hint: Row format: f" P{task.priority} {task.title:<16} {task.status:<6} {tags}". Sort with sorted(self.tasks, key=lambda t: t.priority). ", ".join([]) or "-" gives -. In add, tags is a tuple; pass tags=list(tags).


Show the solution to Exercise 7
"""Exercise 7: Task board (@dataclass, field(default_factory=list), StrEnum,
composition, __len__).

Run:   python ex07.py   (macOS/Linux: python3 ex07.py)
"""
from dataclasses import dataclass, field
from enum import StrEnum, auto


class Status(StrEnum):
    TODO = auto()
    DOING = auto()
    DONE = auto()


@dataclass
class Task:
    title: str
    priority: int                                # 1 = most urgent
    status: Status = Status.TODO
    tags: list[str] = field(default_factory=list)


class TaskBoard:
    """A TaskBoard HAS tasks (composition)."""

    def __init__(self, name: str):
        self.name = name
        self.tasks: list[Task] = []

    def add(self, title: str, priority: int, *tags: str) -> None:
        self.tasks.append(Task(title, priority, tags=list(tags)))

    def move(self, title: str, status: Status) -> None:
        for task in self.tasks:
            if task.title == title:
                task.status = status
                return
        raise ValueError(f"No task called {title!r}")

    def count_by_status(self) -> dict[str, int]:
        return {str(s): sum(t.status is s for t in self.tasks) for s in Status}

    def __len__(self) -> int:
        return len(self.tasks)

    def show(self) -> None:
        print(f"{self.name} ({len(self)} tasks)")
        for task in sorted(self.tasks, key=lambda t: t.priority):
            tags = ", ".join(task.tags) or "-"
            print(f"  P{task.priority} {task.title:<16} {task.status:<6} {tags}")


def main() -> None:
    board = TaskBoard("Website launch")
    board.add("Write homepage", 2, "content")
    board.add("Fix login bug", 1, "backend", "urgent")
    board.add("Pick colours", 3)
    board.move("Fix login bug", Status.DONE)
    board.move("Write homepage", Status.DOING)
    board.show()
    print(board.count_by_status())
    print(board.tasks[2])
    try:
        board.move("Buy domain", Status.DONE)
    except ValueError as e:
        print("Error:", e)


if __name__ == "__main__":
    main()

Exercise 8: Metro card system

Scenario: A metro sells normal cards and student cards with half fare. What to do:

  1. Copy InsufficientBalanceError(Exception) from Part 6.
  2. MetroCard(holder, balance=0) stores the balance in self._balance, has a read-only balance property and a history list (new list per card).
  3. recharge(amount) adds money (raise ValueError if amount <= 0) and appends "+<amount>" to the history.
  4. fare(stations) returns 10 + 5 * stations.
  5. travel(stations) raises InsufficientBalanceError(f"{holder} needs ₹{cost}, card has ₹{balance}") when the fare is more than the balance; otherwise it takes the money and appends "-<cost>".
  6. __str__ returns "<ClassName>(<holder>, ₹<balance>)".
  7. StudentCard(MetroCard) overrides fare to give 50% off: super().fare(stations) // 2.
  8. For each card below, travel 6 stations and then 4 stations, printing Declined: ... on an error. Then recharge Meera's card with 50, travel 4 stations again, and print each card with its history.

Starting data:

cards = [MetroCard("Ravi", 100), StudentCard("Meera", 30)]

Sample output:

Declined: Meera needs ₹15, card has ₹10
MetroCard(Ravi, ₹30) ['-40', '-30']
StudentCard(Meera, ₹45) ['-20', '+50', '-15']

💡 Hint: travel is written only once, in MetroCard. It calls self.fare(...), so a StudentCard automatically uses its own cheaper fare. type(self).__name__ gives the class name for __str__.

Show the solution to Exercise 8
"""Exercise 8: Metro card system (inheritance, overriding, custom exception,
history list, read-only @property, __str__).

Run:   python ex08.py   (macOS/Linux: python3 ex08.py)
"""


class InsufficientBalanceError(Exception):
    """Raised when the card does not have enough money for a trip."""


class MetroCard:
    def __init__(self, holder: str, balance: int = 0):
        self.holder = holder
        self._balance = balance
        self.history: list[str] = []

    @property
    def balance(self) -> int:
        return self._balance

    def recharge(self, amount: int) -> None:
        if amount <= 0:
            raise ValueError("Recharge must be positive")
        self._balance += amount
        self.history.append(f"+{amount}")

    def fare(self, stations: int) -> int:
        return 10 + 5 * stations

    def travel(self, stations: int) -> None:
        cost = self.fare(stations)
        if cost > self._balance:
            raise InsufficientBalanceError(
                f"{self.holder} needs ₹{cost}, card has ₹{self._balance}"
            )
        self._balance -= cost
        self.history.append(f"-{cost}")

    def __str__(self) -> str:
        return f"{type(self).__name__}({self.holder}, ₹{self._balance})"


class StudentCard(MetroCard):
    def fare(self, stations: int) -> int:
        return super().fare(stations) // 2      # 50% off


def main() -> None:
    cards = [MetroCard("Ravi", 100), StudentCard("Meera", 30)]
    for card in cards:
        for stations in (6, 4):
            try:
                card.travel(stations)
            except InsufficientBalanceError as e:
                print("Declined:", e)
    cards[1].recharge(50)
    cards[1].travel(4)
    for card in cards:
        print(card, card.history)


if __name__ == "__main__":
    main()

Common mistakes

Mistake Why it is wrong Fix
Forgetting self in def deposit(amount): Python passes the object first → TypeError: takes 1 positional argument but 2 were given Always write self as the first parameter of an instance method
name = name inside __init__ Only makes a local variable; the object gets nothing self.name = name
A list as a class attribute: items = [] in the class body All objects share one list Create it in __init__: self.items = []
Forgetting super().__init__(...) in a child Parent attributes are never set → AttributeError later Call super().__init__(...) first in the child's __init__
obj.price = -5 with no check Bad data gets in silently Use a @property with a setter that raises ValueError
Writing two methods with the same name for different arguments The second one replaces the first Use default arguments or *args
items: list = [] in a @dataclass Raises ValueError (mutable default) items: list = field(default_factory=list)
Using inheritance for "has-a" (class Car(Engine)) A car is not an engine; the design gets rigid Use composition: self.engine = engine

Quick recap

  • A class is a blueprint; an object is one thing built from it. __init__ sets it up and self is that object.
  • Instance attributes belong to one object; class attributes are shared. @classmethod gets cls (alternative constructors), @staticmethod gets nothing.
  • _name means "internal", __name is mangled; @property adds checks while keeping obj.attr syntax.
  • class Child(Parent): reuses code; override methods and call super() to reuse the parent's version.
  • With many parents, Python searches in MRO order: child, parents left to right, object.
  • Polymorphism and duck typing: same method name, different classes, one loop handles them all.
  • Dunders (__str__, __repr__, __eq__, __lt__, __len__, __add__) plug your class into print, ==, sorted, len and +.
  • ABC + @abstractmethod force children to write methods; @dataclass and Enum/StrEnum remove boilerplate; prefer composition ("has-a") over inheritance ("is-a").

Checklist

  • I can write a class with __init__, instance attributes and methods.
  • I can explain the difference between a class attribute and an instance attribute.
  • I can write a @classmethod alternative constructor and a @staticmethod helper.
  • I can protect a value with @property and a setter that validates it.
  • I can build a child class with super().__init__ and override a method.
  • I can read a class's MRO and explain which method Python will use.
  • I can add __str__, __repr__, __eq__ and __lt__ so my objects print and sort nicely.
  • I can use ABC, @dataclass, Enum and composition, and choose between "is-a" and "has-a".

Search the guide