Inheritance In Python-

  • – In inheritance we can put the common functionalities in one class and we can extend that common class into another classes and wherever it’s required we can use the common methods available inside those common class.
  • – Parent class property can be accessible in child class only if we inherit the parent class into child class but vice versa is not possible means we can’t access child class properties into parent class.
  • 1) Single (A <—-B )
  • 2) Multilevel (A <—B <—– C)
  • 3) Hierarchy
  • 4) Multiple
  • 5) Hybrid

Note-

There is no diamond problem case in Python. PSF developers implemented the solution on this problem in Python.

1) Single (A <—-B )

Ex-

class Parent:
    def display1(self):
        print("Parent")

class Child(Parent):
    def display2(self):
        print("Child")

class TestMain:
    def main():
        objC = Child()
        objC.display1()
        objC.display2()

        objP = Parent()
        objP.display1()
        # objP.display2()  # Error

TestMain.main()	

Output-
	Parent
	Child
	Parent

2) Multilevel (A <—B <—– C)

Ex-

class Grand:
    def display(self):
        print("Grand")

class Parent(Grand):
    def display(self):
        print("Parent")

class Child(Parent):
    def display(self):
        print("Child")

class TestMain(Child):
    def display(self):
        print("TestMain")

    def main():
        obj = TestMain()
        obj.display()

        obj1= Child()
        obj1.display()

TestMain.main()

Output-
	TestMain
	Child

4) Multiple Inheritance-

  • -If child class is overriding the method of parent class then that child class method will called.
  • -In case of parent and child relationship if any method is called then first it search in child class if it is there in child class it will execute that.
  • -If child is not having that method then first it will search that method in “left most parent” first.
  • -If it also doesn’t exist in left most parent then it will search that method in next right class and so on till this method is not found in parent class.

Ex-

class A:
    def display(self):
        print("A")

class B:
    def display(self):
        print("B")

class C(A, B):
    pass

class TestMain:
    def main():
        obj = C()
        obj.display()

TestMain.main()
Output-
A

5) Hybrid- Ex-

class A:
    def display(self):
        print('A')

class B(A):
    def display1(self):
        print('B')

class C(A):
    def display(self):
        print('C')

class D(B, C):
    pass

class TestMain:
    def main():
        obj = D()
        A.display(obj)
        B.display(obj)
        C.display(obj)
        D.display(obj)

TestMain.main()

Output-
	A
	A
	C
	C
Menu