Chapter 7 — Object-Oriented Python

📚 Chapter Overview

Python is a multi-paradigm language, but its OOP features are incredibly flexible. In this chapter, you will learn how to create Classes and Objects, use the __init__ method for initialization, and implement Inheritance to reuse code.

Learning Objectives:

7.1 Classes and the __init__ Method

Part 1 — Definition

A Class is like an object constructor, or a "blueprint" for creating objects. In Python, the __init__() function is a special method (Constructor) that is automatically called when a new object is created. The self parameter represents the instance of the object itself.

Part 2 — Syntax

class MyClass:
    def __init__(self, val):
        self.attr = val

obj = MyClass("Hello")

Part 3 — Example

Problem: Model a "User" with a username and a method to greet.

script.py
class User:
    def __init__(self, username):
        self.username = username

    def greet(self):
        print(f"Welcome back, {self.username}!")

u1 = User("ali_dev")
u1.greet()

Part 4 — Video

Video: Coming Soon


7.2 Inheritance in Python

Part 1 — Definition

Inheritance allows us to define a class that inherits all the methods and properties from another class. The Child Class inherits from the Parent Class. Python also supports Multiple Inheritance, where a class can inherit from more than one parent.

Part 2 — Syntax

class Parent: ...
class Child(Parent): ...

Part 3 — Example

Problem: Create a generic "Animal" class and a specific "Dog" class.

script.py
class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

my_dog = Dog()
my_dog.speak() # Output: Dog barks

Observation: The child class can override methods of the parent class to provide specific behavior.

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "BankAccount" system using OOP.

Requirements

Step-by-Step Process

  1. Define the base class and its constructor.
  2. Implement logic checks inside the withdrawal method.
  3. Inherit the savings class and add the new field.

Expected Deliverables

Solve in Compiler