Python Language / Python Inheritance

Inheritance means acquiring the properties and methods of a parent / base / super class by child/ derived/leaf class.

Example

Program Output
class Parent():
       def pfunction(self):
           print('Parent function')

class Child(Parent):
       def cfunction(self):
          print('Child function')

obj1 = Child()
obj1.pfunction()
obj1.cfunction()
Parent function
Child function

Types of Inheritance
Python supports 4 types of inheritance based on number of child and parent classes involved. They were

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

Python Inheritance

Single Inheritance
Program Output

class Parent:
  def function1(self):
   print("Parent function")

class Child(Parent):
   def function2(self):
    print("Child function")

obj1 = Child()
obj1.function1()
obj1.function1()

Parent function
Child function

Multiple Inheritance
If a single child class inherits a more than one parent class is called as Multiple Inheritance.

Program Output

class Parent:
   def function1(self):
        print("Parent1 function")

class Parent2:
   def function2(self):
        print("Parent2 function")

class Child(Parent , Parent2):
    def function3(self):
        print("Child function")
obj1 = Child()
obj1.function1()
obj1.function2()
obj1.function3()

      Parent1 function      
      Parent2 function      
      Child function      


Multilevel Inheritance
If a single child class is inherited by another child class called as Multilevel Inheritance.

Program Output

class Parent:
      def function1(self):
        print("Parent function")

class Child(Parent):
      def function2(self):
        print("parent to Child2 function")

class Child2(Child):
      def function3(self):
       print("Child2 function")

obj1 = Child2()
obj1.function1()
obj1.function2()
obj1.function3()

Parent function
parent to Child2 function
Child2 function

Hierarchical Inheritance
Hierarchical Inheritance involves multiple inheritance from the same base or parent class.

Program Output

class Parent:
 def function1(self):
  print("function one")

class Child(Parent):
 def function2(self):
  print("function 2")

class Child1(Parent):
 def function3(self):
  print("function 3")

class Child3(Child1):
     def function4(self):
         print("unction 4")

obj1 = Child3()
obj1.function1()

         function one         


Home     Back