Inheritance & Polymorphism
Inheritance allows a new class to inherit attributes and methods from an existing class. Polymorphism allows different classes to be treated as instances of the same general class through a common interface.
Learning Objectives
- 11.4.2.2 Explain the concept of inheritance with examples
- 11.4.2.1 Explain the concept of polymorphism with examples
Conceptual Anchor
The Family Tree Analogy
Inheritance: A child inherits traits (eye color, last name) from parents but can
also have unique traits (a scar) or override inherited ones (different hair color).
Polymorphism: If you tell a Dog, Cat, and Cow to "Speak", they all understand
the command but respond differently (Woof, Meow, Moo). The interface ("Speak") is the same, but
the implementation differs.
Rules & Theory
Inheritance (11.4.2.2)
To inherit from a class, put the parent class name in parentheses when defining the child class.
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
# Dog inherits from Animal
class Dog(Animal):
def bark(self):
print("Woof!")
d = Dog("Buddy")
d.eat() # Inherited from Animal
d.bark() # Defined in Dog super()
Use super().__init__() to call the parent class's constructor inside the child
class. This ensures the parent part of the object is set up correctly.
Polymorphism (11.4.2.1)
Polymorphism allows methods to be used interchangeably, even if the object type is different.
class Cat(Animal):
def speak(self):
return "Meow"
class Dog(Animal):
def speak(self):
return "Woof"
animals = [Cat("Kitty"), Dog("Buddy"), Cat("Luna")]
for animal in animals:
# We treat them all as "Animal", calling separate methods
print(f"{animal.name} says {animal.speak()}")Worked Examples
1 Shapes Hierarchy
import math
class Shape:
def area(self):
pass # Placeholder
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
shapes = [Rectangle(10, 5), Circle(7)]
for s in shapes:
print(f"Area: {s.area():.2f}")2 Game Characters
class Character:
def __init__(self, name):
self.name = name
self.health = 100
def attack(self):
print("Basic attack!")
class Warrior(Character):
def attack(self):
print(f"{self.name} swings a sword!")
class Mage(Character):
def attack(self):
print(f"{self.name} casts a fireball!")
hero = Warrior("Arthur")
wizard = Mage("Merlin")
hero.attack() # Warrior attack
wizard.attack() # Mage attackPitfalls & Common Errors
Overriding Mistakes
If you misspell the method name when trying to override it (e.g., atack vs
attack), Python will treat it as a new method and the old one will still run when
called polymorphically.
Forgetting super().__init__
If a child class defines its own __init__, it DOES NOT automatically call the
parent's __init__. You must call it manually or attributes from the parent won't be
set.
Graded Tasks
What is the syntax for inheritance in Python? What does super() do?
Explain how polymorphism helps when you have a list of different objects.
Create a class Vehicle and subclasses Car and Bike.
Give them a move() method that prints different messages.
Design a hierarchy for a school system: Person -> Student,
Teacher. Add common attributes (name) and specific ones (grade vs subject).