INSTACK 360

OOP: Inheritance & Polymorphism

Write DRY and scalable OOP code. Master Inheritance to share logic between classes and Polymorphism to dynamically alter behavior.

Advanced 5 min read

Inheritance: Don't Repeat Yourself

Imagine you have a Car class and a Motorcycle class. They both have engines, wheels, and drive methods. Instead of writing that identical code twice, you can create a parent Vehicle class, and have the Car and Motorcycle inherit all of its logic automatically.

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

    def honk(self):
        print("Beep beep!")

# Car inherits from Vehicle
class Car(Vehicle):
    def __init__(self, brand, doors):
        super().__init__(brand) # Call parent's constructor
        self.doors = doors

my_car = Car("Honda", 4)
my_car.honk() # Inherited method works!

Polymorphism: Many Forms

Polymorphism allows different child classes to share the same method name, but implement it in entirely different ways. The system dynamically figures out which specific version to call based on the object type.

class Animal:
    def speak(self):
        pass

class Dog(Animal):
    def speak(self): return "Woof!"

class Cat(Animal):
    def speak(self): return "Meow!"

# Polymorphism in action
pets = [Dog(), Cat(), Dog()]
for pet in pets:
    print(pet.speak())