Lesson 22: Advanced Object-Oriented Programming (OOP) Concepts

🎯 Lesson Objective

To understand advanced OOP concepts such as inheritance, polymorphism, abstraction, encapsulation, class methods, static methods, and magic methods in Python.


🧩 1. Review of OOP Basics

Before diving deeper, recall the core OOP structure:

class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color
    
    def drive(self):
        print(f"{self.color} {self.brand} is driving.")

🧱 2. Inheritance (Code Reusability)

Inheritance allows one class to inherit attributes and methods from another.

class Vehicle:
    def __init__(self, brand):
        self.brand = brand

    def start(self):
        print(f"{self.brand} vehicle started.")

class Car(Vehicle):  # Child class
    def horn(self):
        print("Beep! Beep!")

car1 = Car("Toyota")
car1.start()
car1.horn()

Output:

Toyota vehicle started.
Beep! Beep!

βœ… Types of Inheritance:

  • Single β†’ One parent, one child
  • Multiple β†’ Child inherits from multiple parents
  • Multilevel β†’ Grandparent β†’ Parent β†’ Child
  • Hierarchical β†’ One parent, multiple children

βš™οΈ 3. Polymorphism (Many Forms)

Same method name, different behavior depending on object type.

class Dog:
    def sound(self):
        return "Bark"

class Cat:
    def sound(self):
        return "Meow"

for animal in (Dog(), Cat()):
    print(animal.sound())

Output:

Bark
Meow

πŸ”’ 4. Encapsulation (Data Protection)

Encapsulation hides internal data using private attributes (__ prefix).

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance())

Output:

1500

🌐 5. Abstraction (Hiding Complexity)

Use abstract classes to define required methods without implementation.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return 3.14 * self.r * self.r

circle = Circle(5)
print(circle.area())

Output:

78.5

🧰 6. Class Methods and Static Methods

πŸ”Ή Class Method (@classmethod)

Used to modify class-level data.

class Employee:
    company = "ABC Corp"

    @classmethod
    def change_company(cls, new_name):
        cls.company = new_name

Employee.change_company("XYZ Ltd")
print(Employee.company)

Output:

XYZ Ltd

πŸ”Ή Static Method (@staticmethod)

Doesn’t use class or instance; behaves like a utility function.

class Math:
    @staticmethod
    def add(a, b):
        return a + b

print(Math.add(5, 10))

Output:

15

✨ 7. Magic Methods (Dunder Methods)

Magic (or dunder) methods start and end with __.
They let you define behavior for built-in Python operations.

MethodPurposeExample
__init__ConstructorInitialization
__str__String representationprint(obj)
__add__Add two objectsobj1 + obj2
__len__Lengthlen(obj)

βœ… Example:

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages
    
    def __str__(self):
        return f"Book: {self.title}"
    
    def __add__(self, other):
        return self.pages + other.pages

book1 = Book("Python Basics", 200)
book2 = Book("OOP Advanced", 300)

print(book1)          # Uses __str__
print(book1 + book2)  # Uses __add__

Output:

Book: Python Basics
500

πŸ’‘ 8. Real-Life Example – Employee Management System

class Employee:
    raise_percentage = 1.05
    
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    
    def apply_raise(self):
        self.salary *= self.raise_percentage

class Developer(Employee):
    raise_percentage = 1.10

dev = Developer("Sameer", 50000)
dev.apply_raise()
print(dev.salary)

Output:

55000.0

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *