Inheritance
All classes in python are derived from built in ‘object’ class.
Creating a child class from parent class
Class Parent(object):
#attributes+methods
Class child(Parent):
#attributes+methods
class Employee:
bonus=2000
def display(self):
print(‘This is employee class method’)
class Manager(Employee):
bonus=2000
def show(self):
print(‘This is manager class method’)
e1=Employee()
m1=Manager()
[Link]()
[Link]()
print([Link])
Inheritance is very important to implement the code reusability (Write once use many times).
Bank Management System (No inheritance is used)
While using inheritance
How constrictor works in inheritance
By default, parent class constructor is available to the child class.
class Father
def __init__(self):
Print(‘Father class constructor called.’)
[Link]=’Scooter’
class Son(Father):
pass
s=Son()
print(s.__dict__)
class Father
def __init__(self):
Print(‘Father class constructor called.’)
[Link]=’scooter’
class Son(Father):
def __init__(self):
Print(‘Son class constructor called.’)
[Link]=’Honda’
s=Son()
print(s.__dict__)
super() function:
• Using super() function, we can access parent class properties.
• This function returns a temporary object which contains reference to parent class.
• It makes inheritance more manageable and more extensible.
class Father
def __init__(self):
Print(‘Father class constructor called.’)
[Link]=’scooter’
class Son(Father):
def __init__(self):
super().__init__()
Print(‘Son class constructor called.’)
[Link]=’Honda’
s=Son()
print(s.__dict__)
Depending upon the number of child and parent classes involved, Python supports five types
of inheritance that are as follows:
• Single inheritance
• Multilevel inheritance
• Multiple inheritance
• Hierarchical inheritance
• Hybrid inheritance
The arrow in the figure expresses the concept of derivation or inheritance. The directiof n of
the arrow, which goes from the derived class towards the base class, represents that the derived
class inherits all the features (attributes and methods) of the base class, but not vice versa.
Derived class inherits attributes and methods from the parent class.
Let’s understand them one by one with the help of examples.
Single Inheritance:
When a child class inherits the properties (i.e. variables) and behavior (i.e. methods) from only
a single parent class, it is called single inheritance in Python. In the figure, class B inherits from
class A. So, class B is derived class or child class and class A is parent class or base class. This
relationship represents single inheritance.
The general syntax for a single inheritance is as:
class ParentClass:
# ParentClass attributes and methods
class ChildClass(ParentClass):
# ChildClass attributes and methods
PYTHONCopy code
Let’s take a simple example based on the single inheritance.
Example 1:
# Python program to demonstrate single inheritance.
# Creating a base class named Animal.
class Animal:
# Defining a function inside the base class.
def speak(self):
print("Animal speaks")
# Creating a derived class named Dog.
class Dog(Animal):
# Defining a function inside the derived class.
def bark(self):
print("Dog barks")
# Outside the class definition.
# Creating an instance of Dog
dog = Dog()
# Calling functions of both base and derived classes.
[Link]()
[Link]()
# Creating an instance of Animal class.
an = Animal()
# Calling the function of base class.
[Link]()
PYTHONCopy code
Output:
Animal speaks
Dog barks
Animal speaks
Multilevel Inheritance:
When a class is derived from a class which is also derived from another class, it is called
multilevel inheritance. In the figure, class C inherits from class B which inherits from class A.
So, class C is child class of class B (parent class) which is the child class of class A (grandparent
class). This relationship represents multilevel inheritance.
The general syntax for multilevel inheritance is as follows:
class GrandParentClass:
# Grandparent attributes and methods
class ParentClass(GrandParentClass):
# Parent attributes and methods
class ChildClass(ParentClass):
# Child attributes and methods
PYTHONCopy code
Let’s take an example program based on the multilevel inheritance in Python.
Example 2:
# Python program to demonstrate multilevel inheritance.
# This class is a superclass of Parent class.
class Grandparent:
def greet(self):
print("Hello from Grandparent")
# This class is child class of Grandparent class but parent class of Child class.
class Parent(Grandparent):
def talk(self):
print("Parent talks")
# This class is child class of Parent class.
class Child(Parent):
def play(self):
print("Child plays")
# Creating an instance of Grandparent class.
grandparent = Grandparent()
# Accessing method of Grandparent class.
[Link]()
# Creating an instance of Parent class.
parent = Parent()
# Accessing methods of Parent class.
[Link]()
[Link]()
# Creating an instance of Child
child = Child()
# Accessing methods of child class.
[Link]()
[Link]()
[Link]()
PYTHONCopy code
Output:
Hello from Grandparent
Hello from Grandparent
Parent talks
Hello from Grandparent
Parent talks
Child plays
For more practice, go to this tutorial: Advanced multilevel inheritance example
programs
Multiple Inheritance:
Python supports multiple inheritance. If we compare to Java, it does not support
directly through classes. Java supports multiple inheritance through interface, not
via classes.
When a class inherits attributes and methods from more than one parent class, this
type of inheritance is called multiple inheritance in Python. It refers to two or more
parent classes and one child class. In the figure, class C inherits from class A and
class B. So, class C is child class of both class A and class B. This relationship
represents multiple inheritance.
The general syntax for multiple inheritance is as follows:
class ParentClass1:
# ParentClass1 attributes and methods
class ParentClass2:
# ParentClass2 attributes and methods
class ChildClass(ParentClass1, ParentClass2):
# ChildClass attributes and methods
PYTHONCopy code
In the above syntax, ParentClass1 and ParentClass2 are the names of two parent
classes from which we want to inherit attributes and methods. We can specify
multiple parent classes by separating them with commas.
Whereas, ChildClass is the name of the child class that inherits attributes and
methods from both ParentClass1 and ParentClass2. It contains attributes and
methods specific to the child class.
With multiple inheritance, the ChildClass can inherit and use attributes and methods
from both parent classes. This allows us to combine functionality from different
sources and build more complex classes.
Let’s take an example program based on the concept of multiple inheritance in
Python.
Example 3:
# Python program to demonstrate multiple inheritance.
# Create the first parent class.
class A:
def method_A(self):
print("Method A from class A")
# Create the second parent class.
class B:
def method_B(self):
print("Method B from class B")
# Create a child class that inherits methods from both parent classes A and B.
class C(A, B):
def method_C(self):
print("Method C from class C")
# Creating an instance of C
c = C()
# Calling methods of class C.
c.method_A()
c.method_B()
c.method_C()
PYTHONCopy code
Output:
Method A from class A
Method B from class B
Method C from class C
In this example, the class C inherits methods from both classes A and B.
class Person
def __init__(self, nm, ag):
[Link]=nm
[Link]=ag
def display1():
print(“This is Person display method.”)
class Employee(Person)
def __init__(self, nm, ag, sal):
[Link]=nm
[Link]=ag
[Link]=sal
def display2():
print(“This is Employee display method.”)
class Student(Person)
def __init__(self, nm, ag, m):
[Link]=nm
[Link]=ag
[Link]=m
def display2():
print(“This is Student display method.”)
s1=Student(‘Jai’, 21, 99)
e1=Employee(‘Raj’, 23, 60000)
p1=Person(‘Jai’, 21)
s1.display1()
s1.display2() #Attribute Error
p1.display2() #Attribute Error
For more practice, go to this tutorial: Advanced multiple inheritance example
programs
Hierarchical Inheritance:
When more than one child class is derived from a single parent class, this type of
inheritance is called hierarchical inheritance in Python. In above example class B,
class C, and class D are child classes and class A is a parent class. This relationship
represents hierarchical inheritance. The general syntax for hierarchical inheritance
is as follows:
class ParentClass:
# ParentClass attributes and methods
class ChildClass1(ParentClass):
# ChildClass1 attributes and methods
class ChildClass2(ParentClass):
# ChildClass2 attributes and methods
# Additional child classes can also inherit from ParentClass
PYTHONCopy code
In the above syntax, ParentClass is the name of the parent class, containing attributes
and methods that we want to inherit in the child classes.
ChildClass1 and ChildClass2 are the names of the child classes that inherit attributes
and methods from the ParentClass. Each child class can have its own attributes and
methods in addition to those inherited from the parent class.
With hierarchical inheritance, multiple child classes can inherit the properties and
methods from the same parent class. This allows us to reuse code and build a family
of classes that share common properties while having their unique properties.
Let’s take an example program based on the hierarchical inheritance in Python.
Example 4:
# Python program to demonstrate hierarchical inheritance.
# Create a parent class named Vehicle.
class Vehicle:
def start_engine(self):
print("Engine started")
# This class is a subclass of superclass Vehicle and inherits the method from the superclass.
class Car(Vehicle):
def drive(self):
print("Car is driving")
# This class is also a subclass of superclass Vehicle and inherits the method from the superclass.
class Bike(Vehicle):
def ride(self):
print("Bike is riding")
# Creating instances of Car and Bike
car = Car()
bike = Bike()
# Calling methods of child classes using object reference variable car and bike.
car.start_engine()
bike.start_engine()
[Link]()
[Link]()
PYTHONCopy code
Output:
Engine started
Engine started
Car is driving
Bike is riding
In the above example, we can see that class Car and Bike is being inherited from a
single parent class Vehicle. Therefore, both child classes, Car and Bike can access
members of its parent class Vehicle as well as their own class members. But child
classes Car and Bike cannot access the members of each other.
Hybrid Inheritance:
Hybrid inheritance in Python is a combination of hierarchical inheritance and
multiple inheritance within a single program or class hierarchy. It allows us to create
complex class structures that can serve various purposes.
From the above figure, it is clear that above the half portion represents hierarchical
inheritance and below the half portion represents multiple inheritance. This
relationship represents hybrid inheritance.
The general syntax for hybrid inheritance is as follows:
class ParentClass1:
# ParentClass1 attributes and methods.
class ChildClass1(ParentClass1):
# ChildClass1 attributes and methods.
class ChildClass2(ParentClass1):
# ChildClass2 attributes and methods.
class ChildClass3(ParentClass1, ParentClass2):
# ChildClass3 attributes and methods.
PYTHONCopy code
In this simple syntax, ParentClass1 is the superclass of both child classes
ChildClass1 and ChildClass2. This shows the hierarchical inheritance. ChildClass3
demonstrates multiple inheritance, inheriting from both ParentClass1 and
ParentClass2. This is the basic syntax showing the concept of hybrid inheritance.
Let’s take an example program based on the concept of hybrid inheritance.
Example 5:
# Python program to demonstrate hybrid inheritance.
class A:
def m1(self):
print("m1 in class A")
class B(A):
def m2(self):
print("m2 in class B")
class C(A):
def m3(self):
print("m3 in class C")
class D(B, C):
def m4(self):
print("m4 in class D")
# Create an instance of class D.
d = D()
# Calling the methods of class D.
d.m1()
d.m2()
d.m3()
d.m4()
PYTHONCopy code
Output:
m1 in class A
m2 in class B
m3 in class C
m4 in class D
Rule 1: Python first search in child class then goes to parent class. So, priority is child.
Rule 2: MRO follows Depth first left to right approach.
Rule 3: You can use MRO() method for knowing MRO of any class object.