Inheritance in Python
Inheritance is the second major pillar of OOP.
Definition
Inheritance is an OOP mechanism where a new class acquires the properties and methods of an existing class.
In simple words:
Inheritance allows a child class to reuse the features of a parent class.
It helps with code reuse, organization, and extending existing classes.
1. Basic Terminology
Inheritance mainly has two classes:
Parent Class
The existing class whose features are inherited.
Also called:
- Base class
- Superclass
Child Class
The new class that inherits from the parent.
Also called:
- Derived class
- Subclass
Example:
Parent Class ↓ Child Class
2. Basic Syntax
class Parent: # parent members pass class Child(Parent): # child members pass
The important part is:
class Child(Parent):
It means Child inherits from Parent.
3. Simple Inheritance Example
class Animal: def eat(self): print("Animal is eating") class Dog(Animal): def bark(self): print("Dog is barking") dog = Dog() dog.eat() dog.bark()
Output:
Animal is eating Dog is barking
Dog has its own bark() method and also gets eat() from Animal.
4. Why Use Inheritance?
Inheritance is useful when:
Code Reusability
You don't need to write the same code again.
Extending Existing Code
A child class can add new features to the parent class.
Better Organization
Related classes can be organized into a hierarchy.
Easier Maintenance
Common functionality can be kept in one parent class.
5. Parent and Child Members
A child class can have:
Parent ├── Parent attributes ├── Parent methods │ Child ├── Inherited features ├── New attributes └── New methods
Example:
class Vehicle: def start(self): print("Vehicle started") class Car(Vehicle): def drive(self): print("Car is driving")
Car has:
start() → inherited drive() → its own
6. Adding a Constructor in Child Class
A child class can have its own __init__().
class Student: def __init__(self, name): self.name = name class CollegeStudent(Student): def __init__(self, name, course): self.name = name self.course = course
Here, the child constructor initializes both values.
But there is a better way to reuse the parent constructor.
7. #super()
super() is used to access functionality from the parent class.
Example:
class Student: def __init__(self, name): self.name = name class CollegeStudent(Student): def __init__(self, name, course): super().__init__(name) self.course = course
Now:
student = CollegeStudent("Ram", "Computer Science") print(student.name) print(student.course)
Output:
Ram Computer Science
Here:
super().__init__(name)
calls the parent class constructor.
8. Why Use super()?
Without super():
self.name = name
may need to be repeated in the child.
With:
super().__init__(name)
the child can reuse the parent's initialization logic.
This becomes especially useful in larger class hierarchies.
9. Types of Inheritance
Python supports several inheritance structures:
- Single inheritance
- Multiple inheritance
- Multilevel inheritance
- Hierarchical inheritance
- Hybrid inheritance
10. Single Inheritance
One parent class → one child class.
Animal ↓ Dog
Example:
class Animal: def eat(self): print("Eating") class Dog(Animal): def bark(self): print("Barking")
This is called single inheritance.
11. Multiple Inheritance
One child class inherits from more than one parent class.
Father Mother \ / \ / Child
Example:
class Father: def driving(self): print("Driving") class Mother: def cooking(self): print("Cooking") class Child(Father, Mother): pass child = Child() child.driving() child.cooking()
Output:
Driving Cooking
The syntax is:
class Child(Father, Mother):
12. Multilevel Inheritance
Inheritance occurs across multiple levels.
Animal ↓ Mammal ↓ Dog
Example:
class Animal: def eat(self): print("Eating") class Mammal(Animal): def walk(self): print("Walking") class Dog(Mammal): def bark(self): print("Barking")
Now:
dog = Dog() dog.eat() dog.walk() dog.bark()
Output:
Eating Walking Barking
Dog receives features through the entire inheritance chain.
13. Hierarchical Inheritance
One parent class → multiple child classes.
Animal / \ Dog Cat
Example:
class Animal: def eat(self): print("Eating") class Dog(Animal): def bark(self): print("Barking") class Cat(Animal): def meow(self): print("Meowing")
Both Dog and Cat inherit from Animal.
14. Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance types.
For example:
A / \ B C \ / D
This combines hierarchical and multiple inheritance.
Example:
class A: pass class B(A): pass class C(A): pass class D(B, C): pass
Python can support this structure.
15. Method Overriding
A child class can provide its own implementation of a method inherited from the parent.
This is called method overriding.
Example:
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): print("Dog barks")
Now:
dog = Dog() dog.sound()
Output:
Dog barks
The child version of sound() is used instead of the parent version.
16. Calling the Parent Method After Overriding
Sometimes we want to use both the parent and child versions.
We can use super().
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): super().sound() print("Dog barks")
Output:
Animal makes a sound Dog barks
17. Inherited Attributes
A child can access attributes defined by the parent.
class Student: college = "Gyandev Academy" class CSEStudent(Student): pass student = CSEStudent() print(student.college)
Output:
Gyandev Academy
18. Inheritance with Private Members
Private members are not directly inherited in the normal way.
Example:
class Parent: def __init__(self): self.__value = 10 class Child(Parent): pass
The child cannot normally access:
self.__value
directly.
This is because __value uses Python's name mangling.
Protected-style members using _value can be accessed by subclasses, although the underscore is mainly a convention.
19. Checking Inheritance with isinstance()
isinstance() checks whether an object belongs to a particular class or its subclasses.
class Animal: pass class Dog(Animal): pass dog = Dog() print(isinstance(dog, Dog)) print(isinstance(dog, Animal))
Output:
True True
Because a Dog is also an Animal through inheritance.
20. Checking Inheritance with issubclass()
issubclass() checks whether one class is derived from another.
class Animal: pass class Dog(Animal): pass print(issubclass(Dog, Animal))
Output:
True
But:
print(issubclass(Animal, Dog))
Output:
False
21. Method Resolution Order — MRO
When multiple inheritance is used, Python needs to determine which class's method should be used first.
Python uses MRO (Method Resolution Order).
Example:
class A: def show(self): print("A") class B(A): def show(self): print("B") class C(A): def show(self): print("C") class D(B, C): pass
We can check the MRO:
print(D.mro())
Python determines the order in which it searches for methods.
You can also use:
print(D.__mro__)
MRO is particularly important in multiple and hybrid inheritance.
22. Diamond Problem
The diamond problem can occur in multiple inheritance.
Structure:
A / \ B C \ / D
D receives features from both B and C, while both are derived from A.
Python solves method lookup using MRO.
Example:
class A: def show(self): print("A") class B(A): pass class C(A): pass class D(B, C): pass d = D() d.show()
Python uses MRO to determine where show() should be found.
23. Inheritance vs Encapsulation
These are different OOP concepts.
| Encapsulation | Inheritance |
|---|---|
| Controls access to data | Reuses existing class features |
| Protects internal data | Creates parent-child relationships |
| Uses public/protected/private conventions | Uses parent and child classes |
| Focuses on data protection | Focuses on code reuse |
24. Inheritance vs Composition
Inheritance
Represents an is-a relationship.
Dog is an Animal
class Dog(Animal): pass
Composition
Represents a has-a relationship.
Car has an Engine
class Car: def __init__(self): self.engine = Engine()
25. Advantages of Inheritance
1. Code Reusability
Existing code can be reused.
2. Less Duplicate Code
Common functionality can stay in the parent.
3. Easy Extension
Child classes can add new functionality.
4. Better Organization
Related classes can be arranged into a hierarchy.
5. Supports Polymorphism
Inheritance works closely with polymorphism and method overriding.
26. Disadvantages of Inheritance
Inheritance should not be used just because code can technically be reused.
Possible problems include:
- Complex class hierarchies
- Strong dependency between parent and child
- Changes in a parent can affect children
- Multiple inheritance can become difficult to understand
- Deep inheritance chains can make code harder to maintain
For simple has-a relationships, composition can often be more appropriate.
27. Complete Inheritance Structure
Inheritance | +----------------+----------------+ | | | Single Multiple Multilevel | | | A → B A + B → C A → B → C | Hierarchical | A / \ B C | Hybrid | Combination of multiple types
28. Important Inheritance Keywords/Functions
| Feature | Purpose |
|---|---|
class Child(Parent) | Create inheritance |
super() | Access parent functionality |
isinstance() | Check object/class relationship |
issubclass() | Check class inheritance |
mro() | View method resolution order |
__mro__ | View MRO |
Short Definition for Exam
Inheritance is an OOP mechanism in which a child class acquires the properties and methods of a parent class, allowing code reuse and extension of existing functionality.
Main types to remember
Single → Multiple → Multilevel → Hierarchical → Hybrid
And the three concepts commonly studied with inheritance are:
super() → Method Overriding → MRO.