Python course Β· Module 3: Object-Oriented Programming
Inheritance - evolution of species
In this lesson11
Welcome again! Darwin here with a fascinating topic.
In previous lessons you learned to create classes representing species. But in nature, species are not isolated - they are part of a taxonomic hierarchy! Lions and tigers are different species, but both are felines. Felines and canines are different families, but both are mammals.
In object-oriented programming, this hierarchy is called inheritance - one of the most powerful OOP mechanisms!
What is inheritance?
Inheritance allows creating new classes based on existing ones:
- Base class (parent, superclass) - more general, e.g., "Mammal"
- Derived class (child, subclass) - more specific, e.g., "Lion"
The derived class inherits attributes and methods from the base class, and can then:
- Use inherited methods without changes
- Extend base classes (add new methods)
- Override methods - change behavior
# Base class - general Mammal
class Mammal:
def __init__(self, name):
self.name = name
def breathe(self):
return f"{self.name} breathes air"
def move(self):
return f"{self.name} moves"
# Derived class - Lion inherits from Mammal
class Lion(Mammal):
def __init__(self, name, pride_name):
super().__init__(name) # Call parent constructor
self.pride_name = pride_name # Add own attribute
def roar(self):
"""New method - only for lions"""
return f"{self.name} roars: RRROAAR!"
def move(self):
"""Override parent method"""
return f"{self.name} runs across the savanna"
# Usage
simba = Lion("Simba", "Pride Rock")
# Inherited from Mammal
print(simba.breathe()) # "Simba breathes air"
# Overridden in Lion
print(simba.move()) # "Simba runs across the savanna"
# Own Lion method
print(simba.roar()) # "Simba roars: RRROAAR!"
# Own Lion attribute
print(simba.pride_name) # "Pride Rock"Inheritance syntax
You write the base class name in parentheses after the new class name. The child class gets all the parent's methods right away and can add its own:
# Basic syntax
class ChildClass(ParentClass):
pass
# Inheritance with extension
class Animal:
def eat(self):
return "I eat"
class Dog(Animal): # Dog inherits from Animal
def bark(self):
return "Woof woof!"
dog = Dog()
print(dog.eat()) # Inherited: "I eat"
print(dog.bark()) # Own: "Woof woof!"The super() function
super() allows referring to the base class - use it to:
- Call the parent constructor
- Extend the parent method (not completely override it)
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
print(f"Creating animal: {name}")
def describe(self):
return f"{self.name}, age: {self.age}"
class Bird(Animal):
def __init__(self, name, age, wingspan):
# Call Animal constructor
super().__init__(name, age)
# Add own attribute
self.wingspan = wingspan
print(f"Wingspan: {wingspan}m")
def describe(self):
# Extend parent method
base_desc = super().describe() # Call Animal.describe()
return f"{base_desc}, wingspan: {self.wingspan}m"
eagle = Bird("Eagle", 5, 2.3)
# Prints:
# Creating animal: Eagle
# Wingspan: 2.3m
print(eagle.describe()) # "Eagle, age: 5, wingspan: 2.3m"Method Overriding
A derived class can completely replace a parent method:
class Animal:
def speak(self):
return "Animal makes a sound"
class Dog(Animal):
def speak(self):
"""Override completely"""
return "Woof woof!" # Completely new behavior
class Cat(Animal):
def speak(self):
"""Override completely"""
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak()) # "Woof woof!" - not "Animal makes a sound"
print(cat.speak()) # "Meow!"Class hierarchy - taxonomic tree
In nature the hierarchy is deep: Kingdom β Phylum β Class β Order β Family β Genus β Species
# 1. Kingdom Animalia
class Animal:
kingdom = "Animalia"
def __init__(self, name):
self.name = name
def is_alive(self):
return True
def __str__(self):
return f"{self.name} ({self.__class__.__name__})"
# 2. Phylum Chordata
class Chordate(Animal):
phylum = "Chordata"
def has_notochord(self):
return True
# 3. Class Mammalia
class Mammal(Chordate):
class_name = "Mammalia"
def __init__(self, name, fur_color):
super().__init__(name)
self.fur_color = fur_color
def nurse_young(self):
return f"{self.name} nurses its young with milk"
def regulate_temperature(self):
return f"{self.name} maintains constant body temperature"
# 4. Order Carnivora
class Carnivore(Mammal):
order = "Carnivora"
def __init__(self, name, fur_color, hunting_style):
super().__init__(name, fur_color)
self.hunting_style = hunting_style
def hunt(self):
return f"{self.name} hunts using: {self.hunting_style}"
# 5. Family Felidae
class Feline(Carnivore):
family = "Felidae"
def retract_claws(self):
return f"{self.name} retracts its claws"
def purr(self):
return f"{self.name} purrs"
# 6. Species Panthera leo (Lion)
class Lion(Feline):
species = "Panthera leo"
def __init__(self, name, fur_color, pride_name):
super().__init__(name, fur_color, "pack hunting")
self.pride_name = pride_name
def roar(self):
return f"{self.name} roars loudly!"
def lead_pride(self):
return f"{self.name} leads the {self.pride_name} pride"
# Usage - the lion has access to ALL methods in the hierarchy!
simba = Lion("Simba", "golden", "Pride Rock")
# From Animal
print(simba.is_alive()) # True
# From Chordate
print(simba.has_notochord()) # True
# From Mammal
print(simba.nurse_young()) # "Simba nurses its young with milk"
print(simba.regulate_temperature()) # "Simba maintains constant body temperature"
# From Carnivore
print(simba.hunt()) # "Simba hunts using: pack hunting"
# From Feline
print(simba.retract_claws()) # "Simba retracts its claws"
print(simba.purr()) # "Simba purrs"
# Own Lion methods
print(simba.roar()) # "Simba roars loudly!"
print(simba.lead_pride()) # "Simba leads the Pride Rock pride"
# Attributes
print(simba.kingdom) # "Animalia"
print(simba.species) # "Panthera leo"
print(simba.fur_color) # "golden"Checking class relationships
Python offers functions to check the hierarchy:
class Animal:
pass
class Mammal(Animal):
pass
class Lion(Mammal):
pass
simba = Lion()
# isinstance() - check if object is an instance of a class
print(isinstance(simba, Lion)) # True
print(isinstance(simba, Mammal)) # True - Lion inherits from Mammal
print(isinstance(simba, Animal)) # True - Lion inherits from Animal (through Mammal)
print(isinstance(simba, str)) # False
# issubclass() - check if a class inherits from another class
print(issubclass(Lion, Mammal)) # True
print(issubclass(Lion, Animal)) # True
print(issubclass(Mammal, Lion)) # False
print(issubclass(Lion, Lion)) # True - a class is a subclass of itself
# type() - return the exact type
print(type(simba)) # <class '__main__.Lion'>
print(type(simba) == Lion) # True
print(type(simba) == Mammal) # False - simba is a Lion, not a MammalMultiple Inheritance
Python allows inheriting from multiple classes at once - a class can have multiple parents!
class Swimmer:
def swim(self):
return f"{self.name} swims"
class Flyer:
def fly(self):
return f"{self.name} flies"
class Walker:
def walk(self):
return f"{self.name} walks"
# Duck inherits from three classes!
class Duck(Swimmer, Flyer, Walker):
def __init__(self, name):
self.name = name
def quack(self):
return f"{self.name}: Quack quack!"
donald = Duck("Donald")
# Has access to methods from all base classes
print(donald.swim()) # "Donald swims"
print(donald.fly()) # "Donald flies"
print(donald.walk()) # "Donald walks"
print(donald.quack()) # "Donald: Quack quack!"MRO - Method Resolution Order
When a class inherits from multiple parents, Python uses MRO (Method Resolution Order) to determine the method search 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): # Inherits from B and C
pass
d = D()
print(d.method()) # "B" - Python searches: D β B β C β A
# Check MRO
print(D.__mro__)
# (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>,
# <class '__main__.A'>, <class 'object'>)
# Or more readable:
print(D.mro())Rule: Python searches classes from left to right, from most specific to most general.
Safari example - species hierarchy with observations
Now the whole safari hierarchy: a shared Species class, below it mammals and birds, then carnivores and herbivores, and at the very bottom felines and canines. Each level adds its own attributes and extends describe() with super().
class Species:
"""
Base class for all species in the Safari catalog
"""
kingdom = "Animalia"
total_species_count = 0
def __init__(self, scientific_name, common_name, habitat):
self.scientific_name = scientific_name
self.common_name = common_name
self.habitat = habitat
self.observations = []
Species.total_species_count += 1
def add_observation(self, date, location, count, notes=""):
"""Add a field observation"""
self.observations.append({
"date": date,
"location": location,
"count": count,
"notes": notes
})
def get_total_observed(self):
"""Total number of observed individuals"""
return sum(obs["count"] for obs in self.observations)
def describe(self):
"""Basic species description"""
return f"{self.common_name} ({self.scientific_name})"
def __str__(self):
return self.describe()
class Mammal(Species):
"""
Class representing mammals - extends Species
"""
class_name = "Mammalia"
def __init__(self, scientific_name, common_name, habitat, fur_color, gestation_days):
# Call Species constructor
super().__init__(scientific_name, common_name, habitat)
# Add mammal-specific attributes
self.fur_color = fur_color
self.gestation_days = gestation_days
def nurse_young(self):
"""Mammals nurse their young with milk"""
return f"{self.common_name} nurses its young (gestation lasts {self.gestation_days} days)"
def describe(self):
"""Extend description with mammal information"""
base = super().describe() # Call Species.describe()
return f"{base} | Mammal | Fur: {self.fur_color}"
class Bird(Species):
"""
Class representing birds
"""
class_name = "Aves"
def __init__(self, scientific_name, common_name, habitat, wingspan_m, can_fly=True):
super().__init__(scientific_name, common_name, habitat)
self.wingspan_m = wingspan_m
self.can_fly = can_fly
def lay_eggs(self):
return f"{self.common_name} lays eggs"
def describe(self):
base = super().describe()
flight_status = "flying" if self.can_fly else "flightless"
return f"{base} | {flight_status} Bird | Wingspan: {self.wingspan_m}m"
class Carnivore(Mammal):
"""
Predators - inherit from Mammal
"""
order = "Carnivora"
def __init__(self, scientific_name, common_name, habitat, fur_color,
gestation_days, hunting_style, pack_hunter=False):
super().__init__(scientific_name, common_name, habitat, fur_color, gestation_days)
self.hunting_style = hunting_style
self.pack_hunter = pack_hunter
def hunt(self):
style = "in a pack" if self.pack_hunter else "alone"
return f"{self.common_name} hunts {style} using: {self.hunting_style}"
def calculate_danger_level(self):
"""Calculate danger level (1-10)"""
base_danger = 5
if self.pack_hunter:
base_danger += 3
if "ambush" in self.hunting_style:
base_danger += 2
return min(10, base_danger)
def describe(self):
base = super().describe()
danger = self.calculate_danger_level()
return f"{base} | Predator | Danger: {danger}/10"
class Herbivore(Mammal):
"""
Herbivores - inherit from Mammal
"""
def __init__(self, scientific_name, common_name, habitat, fur_color,
gestation_days, diet_type):
super().__init__(scientific_name, common_name, habitat, fur_color, gestation_days)
self.diet_type = diet_type # "leaves", "grass", "fruit"
def graze(self):
return f"{self.common_name} eats {self.diet_type}"
def describe(self):
base = super().describe()
return f"{base} | Herbivore | Diet: {self.diet_type}"
class Feline(Carnivore):
"""
Felines - inherit from Carnivore
"""
family = "Felidae"
def __init__(self, scientific_name, common_name, habitat, fur_color,
gestation_days, has_mane=False, pride_size=1):
super().__init__(
scientific_name, common_name, habitat, fur_color,
gestation_days, "ambush and chase", pack_hunter=(pride_size > 1)
)
self.has_mane = has_mane
self.pride_size = pride_size
def retract_claws(self):
return f"{self.common_name} retracts its sharp claws"
def stalk_prey(self):
return f"{self.common_name} stalks its prey silently"
def describe(self):
base = super().describe()
social = f"social ({self.pride_size})" if self.pride_size > 1 else "solitary"
return f"{base} | Feline | {social}"
class Canine(Carnivore):
"""
Canines - inherit from Carnivore
"""
family = "Canidae"
def __init__(self, scientific_name, common_name, habitat, fur_color,
gestation_days, pack_size=1):
super().__init__(
scientific_name, common_name, habitat, fur_color,
gestation_days, "endurance pursuit", pack_hunter=(pack_size > 1)
)
self.pack_size = pack_size
def howl(self):
return f"{self.common_name} howls to the pack"
def track_scent(self):
return f"{self.common_name} tracks prey by scent"
def describe(self):
base = super().describe()
social = f"pack ({self.pack_size})" if self.pack_size > 1 else "solitary"
return f"{base} | Canine | {social}"
# === DEMONSTRATION - Creating Safari hierarchy ===
print("=== SAFARI SPECIES CATALOG - HIERARCHY ===\n")
# Felines
lion = Feline(
scientific_name="Panthera leo",
common_name="Lion",
habitat="savanna",
fur_color="golden",
gestation_days=110,
has_mane=True,
pride_size=15
)
leopard = Feline(
scientific_name="Panthera pardus",
common_name="Leopard",
habitat="savanna and forests",
fur_color="yellow with black spots",
gestation_days=90,
has_mane=False,
pride_size=1 # Solitary
)
# Canines
wild_dog = Canine(
scientific_name="Lycaon pictus",
common_name="African Wild Dog",
habitat="savanna",
fur_color="mottled",
gestation_days=70,
pack_size=20
)
# Herbivores
elephant = Herbivore(
scientific_name="Loxodonta africana",
common_name="African Elephant",
habitat="savanna",
fur_color="gray",
gestation_days=645, # Longest gestation!
diet_type="leaves, bark, grass"
)
giraffe = Herbivore(
scientific_name="Giraffa camelopardalis",
common_name="Giraffe",
habitat="savanna",
fur_color="yellow with brown patches",
gestation_days=440,
diet_type="acacia leaves"
)
# Birds
eagle = Bird(
scientific_name="Aquila rapax",
common_name="Tawny Eagle",
habitat="savanna",
wingspan_m=2.1,
can_fly=True
)
# Add observations
lion.add_observation("2024-01-15", "Serengeti", 12, "Pride hunting wildebeest")
lion.add_observation("2024-01-20", "Masai Mara", 8, "Family with cubs")
leopard.add_observation("2024-01-16", "Rocky area", 1, "Solitary male")
wild_dog.add_observation("2024-01-18", "Savuti", 18, "Pack hunting")
elephant.add_observation("2024-01-17", "Amboseli", 45, "Large herd at waterhole")
giraffe.add_observation("2024-01-19", "Tarangire", 23, "Giraffes feeding on acacias")
eagle.add_observation("2024-01-21", "Sky over savanna", 3, "Pair with juvenile")
# Display descriptions - each uses its own version of describe()
print("LION:")
print(f" {lion.describe()}")
print(f" {lion.hunt()}")
print(f" {lion.stalk_prey()}")
print(f" {lion.retract_claws()}")
print(f" {lion.nurse_young()}")
print(f" Observations: {lion.get_total_observed()} individuals")
print(f"\nLEOPARD:")
print(f" {leopard.describe()}")
print(f" {leopard.hunt()}")
print(f" Danger level: {leopard.calculate_danger_level()}/10")
print(f"\nAFRICAN WILD DOG:")
print(f" {wild_dog.describe()}")
print(f" {wild_dog.hunt()}")
print(f" {wild_dog.howl()}")
print(f" {wild_dog.track_scent()}")
print(f"\nELEPHANT:")
print(f" {elephant.describe()}")
print(f" {elephant.graze()}")
print(f" Observations: {elephant.get_total_observed()} individuals")
print(f"\nGIRAFFE:")
print(f" {giraffe.describe()}")
print(f" {giraffe.graze()}")
print(f"\nEAGLE:")
print(f" {eagle.describe()}")
print(f" {eagle.lay_eggs()}")
# Check hierarchy
print(f"\n=== CLASS HIERARCHY ===")
print(f"Lion inherits from Feline? {isinstance(lion, Feline)}")
print(f"Lion inherits from Carnivore? {isinstance(lion, Carnivore)}")
print(f"Lion inherits from Mammal? {isinstance(lion, Mammal)}")
print(f"Lion inherits from Species? {isinstance(lion, Species)}")
print(f"Lion inherits from Bird? {isinstance(lion, Bird)}")
print(f"\nMRO Feline: {[cls.__name__ for cls in Feline.mro()]}")
# ['Feline', 'Carnivore', 'Mammal', 'Species', 'object']
print(f"\n=== STATISTICS ===")
print(f"Total species in catalog: {Species.total_species_count}")
# Polymorphism - each species has its own implementation of describe()
print(f"\nAll species:")
all_animals = [lion, leopard, wild_dog, elephant, giraffe, eagle]
for animal in all_animals:
print(f" - {animal.describe()}")Practical inheritance rules
1. When to use inheritance?
Use inheritance when:
- "is-a" relationship: Lion is a Mammal
- You want to reuse code from the base class
- You're creating a type hierarchy
DON'T use inheritance when:
- "has-a" relationship: Car has an Engine (use composition!)
- Classes don't share a common nature
- You just want to borrow a few methods
# Good - "is-a" relationship
class Animal:
pass
class Dog(Animal): # Dog IS an animal
pass
# Bad - "has-a" relationship
class Engine:
def start(self):
return "Engine started"
class Car(Engine): # NO! Car IS NOT an engine!
pass
# Good - composition
class Car:
def __init__(self):
self.engine = Engine() # Car HAS an engine
def start(self):
return self.engine.start()2. Liskov Substitution Principle (LSP)
An object of a derived class should be able to replace an object of the base class without changing program correctness.
def make_sound(animal):
"""Function accepts any Animal"""
print(animal.speak())
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# LSP - Dog and Cat can replace Animal
make_sound(Dog()) # "Woof!" - works
make_sound(Cat()) # "Meow!" - works3. Avoid deep hierarchies
Every level of inheritance is one more class you have to read to understand an object. Compare six empty levels with three that mean something:
# Bad - hierarchy too deep
class A:
pass
class B(A):
pass
class C(B):
pass
class D(C):
pass
class E(D):
pass
class F(E): # 6 levels!
pass
# Good - flat, understandable hierarchy
class Animal:
pass
class Mammal(Animal):
pass
class Lion(Mammal):
passThree levels, Animal β Mammal β Lion, are readable at a glance. When a hierarchy grows beyond three or four levels, check whether some behavior would fit better in composition.
Summary
In this lesson you learned:
- What inheritance is and why it's powerful
- How to create derived classes with
class Child(Parent) - Using
super()to call parent methods - Overriding and extending methods
- Building class hierarchies (taxonomic tree)
- Checking relationships with
isinstance()andissubclass() - Multiple inheritance and MRO
- Practical rules: when to use inheritance and when not to
Checkpoint
Before moving on:
- You understand the difference between base and derived classes
- You can use
super()in a constructor - You know how to override a parent method
- You understand hierarchy and multi-level inheritance
- You know the difference between "is-a" (inheritance) and "has-a" (composition)
Safari Analogy: A class hierarchy is an evolutionary tree - each descendant inherits traits from ancestors but develops its own unique adaptations!
In the next lesson Darwin will teach you encapsulation - how to protect sensitive species data from unauthorized access!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you define a Cat class that inherits from Animal?
2. What is super().__init__() used for?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the elements in the correct order:
- Code editor
Create a Tiger class inheriting from Animal(name, species): in __init__, call super().__init__(name, species) and add a stripes attribute. Create one tiger
- Code editor
The Animal class has a speak() method. Override it in the Tiger(Animal) class so that it displays 'Rrrrr!'. Create a tiger and call speak()
- Horizontal ordering
Arrange the header of a Tiger class that inherits from Animal:
- Click in order
Click the parts of a call to the parent class constructor with the argument name: