Types of Inheritance


Type of Inheritance

Depending upon the number of child and parent classes involved, there are four types of inheritance in python.

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


Let us understand one by one .....

Single Inheritance

      Where a child class inherits only a single parent class.




Example

class Parent:                 #Super class

        def func1(self):

                print("This is a function one")

class Child(Parent):        # sub class

        def func2(self):

                print("This is function two")

ob=Child()         # object creation

ob.func1()

ob.func2()


Output

This is function one

This is function two

Multiple Inheritance


When a child class inherits from more than one parent class. In multiple Inheritance one child class can inherit multiple parent classes.



Example

class Parent1:

        def func1(self):

                print("This is function one")

class Parent2:

        def func2(self):

                print("This is function two")

class Child(Parent1, Parent2):          # Multiple Inheritance

        def func3(self):

                print("This is function three")

ob=Child()

ob.func1()

ob.func2()

ob.func3()

Output

This is function one

This is function two

This is function three

Multilevel Inheritance

When a child class becomes a parent class for another child class. There is so many levels for inheritance so It is called multilevel Inheritance.




Example

class Parent:

        def func1(self):

                print("This is function one")

class Child1(Parent):

        def func2(self):

                print("This is function two")

class Child2(Child):

        def func3(self):

                print("This is function three")

ob=Child2()

ob.func1()

ob.func2()

ob.func3()

Output

This is function one

This is function two

This is function three

Hierarchical Inheritance


  Hierarchical inheritance involves multiple inheritance from the same base of parent class.


Example


class Parent:

        def func1(self):

                print("This is function one")

class Child(Parent):

        def func2(self):

                print("This is function two")

class Child2(Parent):

        def func3(self):

                print("This is function three")

ob=Child()

ob1=Child2()

ob.func1()

ob.func2()

ob1.func3()

Output

This is function one

This is function two

This is function three








                        













              

No comments:

Post a Comment