Python 24-Day Course - Day 14: Inheritance and Polymorphism

Day 14: Inheritance and Polymorphism

Basic Inheritance

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclasses must implement this")

class Dog(Animal):
    def speak(self):
        return f"{self.name}: Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name}: Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak())  # Buddy: Woof!
print(cat.speak())  # Whiskers: Meow!

Calling Parent with super()

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

    def info(self):
        return f"{self.name}, Salary: {self.salary}"

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

    def info(self):
        base = super().info()
        return f"{base}, Department: {self.department}"

mgr = Manager("Kim", 80000, "Engineering")
print(mgr.info())  # Kim, Salary: 80000, Department: Engineering

Polymorphism

class Shape:
    def area(self):
        raise NotImplementedError

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return 3.14159 * self.radius ** 2

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height

# Polymorphism: same interface, different behavior
shapes = [Circle(5), Rectangle(4, 6), Circle(3)]
for shape in shapes:
    print(f"Area: {shape.area():.2f}")

isinstance and issubclass

print(isinstance(dog, Dog))      # True
print(isinstance(dog, Animal))   # True
print(issubclass(Dog, Animal))   # True
print(issubclass(Dog, Cat))      # False

Today’s Exercises

  1. Create a Vehicle base class with Car, Bicycle, and Truck subclasses.
  2. Build a shape inheritance hierarchy and calculate the total area of multiple shapes.
  3. Implement a Payment base class with CardPayment, CashPayment, etc.

Was this article helpful?