Back to Blog

Inheritance, Polymorphism, Duck Typing (Beginner Friendly) - Python OOP Tutorial #20

Sandy LaneSandy Lane

Video: Inheritance, Polymorphism, Duck Typing (Beginner Friendly) - Python OOP Tutorial #20 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Inheritance, Polymorphism, Duck Typing in Python

This tutorial introduces core concepts of Python object-oriented programming: inheritance, polymorphism, and duck typing. You'll learn how to extend parent classes, override methods, and write flexible code that works with different object types sharing the same interface.

Code

import math

# Inheritance: Vehicle is the parent class
class Vehicle:
  def __init__(self, make, model, year):
    self.make = make
    self.model = model
    self.year = year

# Car inherits from Vehicle and extends it
class Car(Vehicle):
  def __init__(self, make, model, year, doors):
    super().__init__(make, model, year)  # Reuse Vehicle's initializer
    self.doors = doors

  # Override method to customize behavior
  def description(self):
    return f"{self.year} {self.make} {self.model} with {self.doors} doors"

# Polymorphism: base Shape class with area method
class Shape:
  def area(self):
    return 0

class Circle(Shape):
  def __init__(self, radius):
    self.radius = radius

  def area(self):
    return math.pi * 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

# Duck typing: any object with area() method works here
def total_area(shapes):
  return sum(shape.area() for shape in shapes)

# Example usage
car = Car("Toyota", "Camry", 2022, 4)
print(car.description())  # Polymorphic method from Car

shapes = [Circle(5), Rectangle(4, 6)]
print(f"Total area: {total_area(shapes)}")  # Works because both have area()

# Type checking with isinstance and issubclass
print(isinstance(car, Vehicle))  # True
print(issubclass(Car, Vehicle))  # True

Key Points

  • Inheritance allows a class to reuse and extend the functionality of a parent class.
  • Use super().__init__() to call the parent class constructor and avoid code duplication.
  • Polymorphism lets different subclasses implement the same method differently, enabling flexible code.
  • Duck typing means functions work on any object with the required methods, regardless of inheritance.
  • isinstance() and issubclass() help check object and class relationships for safer type handling.