Inheritance and Polymorphism

Intermediate PythonOOPFree Lesson

Advertisement

Introduction

Inheritance allows creating new classes based on existing ones. Polymorphism lets objects of different types be treated uniformly.

Method Resolution Order

class A:
    def method(self):
        return "A"

class B(A):
    def method(self):
        return "B"

class C(A):
    def method(self):
        return "C"

class D(B, C):
    pass

d = D()
print(d.method())  # B (MRO: D -> B -> C -> A)

super() Function

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

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # Call parent's __init__
        self.age = age

Abstract Classes

from abc import ABC, abstractmethod

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

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

Practice Problems

  1. Create a shape hierarchy with area calculations
  2. Use super() to call parent methods
  3. Implement abstract base class
  4. Demonstrate method overriding
  5. Show how MRO works with multiple inheritance

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement