Modeling Animals with Inheritance
An educational walkthrough of class inheritance using Mammal and Dolphin
This guide demonstrates how object-oriented programming models real-world hierarchies. We start with a general animal class and extend it into a more specific one, observing how initialization order, inherited behavior, and overridden properties work together.
Problem Overview
You are working with a system designed to model different types of animals. The goal is to create:
- A general animal class called
Mammal - A specific animal subclass called
Dolphin
The example focuses on how subclasses reuse and modify parent class behavior.
Class Design Breakdown
๐พ General Animal Class: Mammal
The Mammal class represents a general category of animals.
Every mammal has a category property identifying it as a mammal.
class Mammal:
def __init__(self):
self.category = "mammal"
def greet(self):
print(f"I am a {self.category}")
๐ฌ Specific Animal Class: Dolphin
The Dolphin class inherits from Mammal.
During initialization, it:
- Calls the parent (
Mammal) initializer - Immediately performs a greeting
- Then updates its category to dolphin
class Dolphin(Mammal):
def __init__(self):
super().__init__()
self.greet()
self.category = "dolphin"
Execution Flow Explained
⚙️ Initialization Sequence
When a Dolphin object is created, the following happens:
- The
Mammalconstructor sets the category to"mammal" - The inherited
greet()method is called - The category is then updated to
"dolphin"
๐ป CLI Output Example
Running the following code:
d = Dolphin() d.greet()
Produces this output:
I am a mammal I am a dolphin
Why This Matters
This example illustrates a critical object-oriented concept: subclasses inherit behavior first, then customize it.
The order of operations during initialization affects observable behavior, which is why the first greeting identifies the dolphin as a mammal.
๐ก Key Takeaways
- Subclasses reuse parent logic through inheritance
super()ensures proper initialization order- State changes after initialization affect future behavior
- Method calls during construction reflect the current object state