Inheritance & Polymorphism

Inheritance allows a class (Child) to inherit attributes and methods from another class (Parent).

1. Basic Inheritance

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

class Dog(Animal): # Inherits from Animal
    def speak(self):
        print("Woof!")

my_dog = Dog()
my_dog.speak() # Woof!

2. Using super()

Use the super() function to call methods from the parent class, which is common in constructors.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

class Manager(Employee):
    def __init__(self, name, salary, team_size):
        super().__init__(name, salary)
        self.team_size = team_size

3. Polymorphism

Polymorphism allows different classes to be treated as instances of the same class through the same interface (method name).

shapes = [Circle(5), Square(10)]
for shape in shapes:
    print(shape.area()) # Both have .area() but different logic
Pro Tip: Prefer Composition over Inheritance for simpler and more flexible designs when suitable.