Inheritance in Python

Inheritance is important part of object oriented programming. Inheritance provide code reusability to the program. We can access property of any class and use them.

In inheritance child class can access all data and functions of parent class.

class parentClass():
     def __init__(self, a,b)
         self.a = a
         self.b = b
      def sum():
         print(self.a + self.b)

class childClass(parentClass):
      def multiply()
          print(self.a * self.b)

c1 = childClass(10,20)
c1.sum()

Output: 30

c1.multiply()
Output: 200

What is multiple inheritance ?

When one class can inherit property of multiple class, it is called multiple inheitence.

class parentClass():
     def __init__(self, a,b)
         self.a = a
         self.b = b
      def sum():
         print(self.a + self.b)

class parentClass2():
      def multiply()
          print(self.a * self.b)

class childClass(parentClass, parentClass2):
      def showResult()
          print(Show Sum and multiply)

c1 = childClass(10,20)
c1.showResult()
c1.sum()
c1.multiply()

Output: 
# Show Sum and multiply
# 30
# 200

What is multilevel inheritance ?

When grandparent class property inherits by parent class and parent class property, inherit from child class, it is called multilevel inheritance.

class AClass():
    def readA():
     print("I am A class")

class BClass():
     def readB():
      print("I am B class")

class CClass(parentClass, parentClass2):
      def readC():
         print("I am C class")

c1 = CClass()
c1.readA()
c1.readB()
c1.readC()

Output: 
# I am A class
# I am B class
# I am C class

Leave a Comment

Your email address will not be published. Required fields are marked *