Concept
Inheritance is a mechanism to create a new class (subclass) that inherits attributes and methods from an existing class (parent class). It allows for code reuse and establishes a relationship between classes.| Type | Description | Example |
|---|---|---|
| Single Inheritance | A subclass inherits from one parent class. | class Dog(Animal): pass |
| Multiple Inheritance | A subclass inherits from multiple parent classes. | class FlyingDog(Dog, Bird): pass |
| Multilevel Inheritance | A chain of inheritance across three or more levels. | Animal → Mammal → Dog |
| Hierarchical Inheritance | Multiple subclasses inherit from a single parent class. | Animal → Dog, Cat, Bird |
| Hybrid Inheritance | A combination of two or more types of inheritance. | Dog and Bird both extend Animal; FlyingDog extends both. |
Implementation
Single Inheritance
Single Inheritance
A subclass inherits from one parent class. Use
super().__init__() to call the parent constructor.animal.py
super().__init__(name, age) calls the constructor of the parent class (Animal) to initialize inherited attributes. isinstance(dog, Animal) returns True because Dog is a subclass of Animal.Multiple Inheritance
Multiple Inheritance
A subclass inherits from multiple parent classes. The order of method resolution is determined by the Method Resolution Order (MRO), which follows the C3 linearization algorithm.The MRO for
animal.py
FlyingDog is: FlyingDog → Dog → BirdYou can inspect MRO at runtime:Multilevel Inheritance
Multilevel Inheritance
A chain where a subclass inherits from a parent, which itself inherits from another parent.
animal.py
Hierarchical Inheritance
Hierarchical Inheritance
Multiple subclasses share a single parent class.
animal.py
Hybrid Inheritance
Hybrid Inheritance
A combination of multiple inheritance types. Here
Dog and Bird both extend Animal, and FlyingDog extends both.animal.py