Python Inheritance

What is Inheritance?

Inheritance allows one class (child or derived class) to inherit the properties and behaviors (methods and attributes) of another class (parent or base class).

It helps with code reuse, organization, and implementing object-oriented programming principles.

Syntax

class Parent:
   # parent class code
class Child(Parent):
   # child class code (inherits from Parent)

Example 1: Simple Inheritance

class Animal:
   def speak(self):
       print("Animal speaks")
class Dog(Animal):
   def bark(self):
       print("Dog barks")
d = Dog()
d.speak()  # Inherited from Animal
d.bark()   # Defined in Dog

Output:

Animal speaks
Dog barks

Explanation:

  • Dog class inherits from Animal.
  • It gains access to speak() from the parent class without redefining it.

 Example 2: Constructor in Parent and Child

class Person:
   def __init__(self, name):
       self.name = name
   def show(self):
       print(f"Name: {self.name}")
class Student(Person):
   def __init__(self, name, roll):
       super().__init__(name)  # Call parent constructor
       self.roll = roll
   def display(self):
       print(f"Roll Number: {self.roll}")
s = Student("Simran", 101)
s.show()
s.display()

Output:

Name: Simran
Roll Number: 101

Explanation:

  • super().__init__(name) calls the constructor of the Person class.
  • Student adds extra functionality (roll and display()).

Types of Inheritance in Python

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Multiple Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

Example 3: Multiple Inheritance

class Father:
   def skills(self):
       print("Programming")
class Mother:
   def skills(self):
       print("Designing")
class Child(Father, Mother):
   def show(self):
       print("Learning")
c = Child()
c.show()
c.skills()  # Will use Father's method due to Method Resolution Order (MRO)

Output:

Learning
Programming

Key Concepts

TermDescription
super()Used to call parent methods/constructors
MROMethod Resolution Order in multiple inheritance
ReusabilityInheritance promotes code reuse
OverridingChild class can redefine parent methods