Published Sept. 7, 2023, 1:09 a.m.
🎓 Multi-Level Inheritance: Exploring Multi-Level Inheritance with Animal Traits in Python🐾
Multi-Level Inheritance is a way of creating a family tree of animals with different characteristics 🌳. Each animal inherits characteristics from its parent, who also inherits characteristics from its grandparent. In Python, this is done by using Multi-Level Inheritance, where a subclass inherits from a superclass that inherits from another superclass.
Textual Diagram:
🦁 Animal (Superclass) 🦁
┌────────────────────┐
│ speak() │
└────────────────────┘
^
|
|
|
|
v
🐾 Mammal (Subclass) 🐾
┌────────────────────┐
│ run() │
└────────────────────┘
^
|
|
|
|
v
🐕 Dog (Subclass) 🐕
┌────────────────────┐
│ bark() │
└────────────────────┘
Diagram Explanation:
Dog
class inherits from the Mammal
class and has access to its attributes and methods 🚀.Mammal
class inherits from the Animal
class and has access to its attributes and methods 🚀.Animal
class is the top-level superclass that defines the common characteristic of all animals 🌟.This example demonstrates how each subclass inherits and modifies characteristics from its superclass, creating a hierarchical structure of classes in Python 🐍.
Example:
# Define a superclass called "Animal"
class Animal:
def speak(self):
print("Animal speaks")
# Define a subclass called "Mammal" that inherits from "Animal"
class Mammal(Animal):
def run(self):
print("Mammal runs")
# Define another subclass called "Dog" that inherits from "Mammal"
class Dog(Mammal):
def bark(self):
print("Dog barks")
# Create an object of the "Dog" class
dog = Dog()
# Access methods from all levels of the inheritance hierarchy
dog.speak() # This invokes the "speak" method from the "Animal" class
dog.run() # This invokes the "run" method from the "Mammal" class
dog.bark() # This invokes the "bark" method from the "Dog" class
Code Explanations:
Animal
class, which represents general animal characteristics, with a speak
method.Mammal
class inherits from Animal
and adds a run
method, which is a particular characteristic of mammals.Dog
class, a subclass of Mammal
, inherits both speak
from Animal
and run
from Mammal
, and adds its own method bark
, which is a specific characteristic of dogs.Dog
class and show Multi-Level Inheritance by calling methods from different levels of the hierarchy.