Inheritance Multi-Level and Multiple in Python

In this class, we discuss inheritance multi-level and multiple in python.

For Complete YouTube Video: Click Here

Inheritance in Python

The reader should have prior knowledge of class, object, and method. Click here.

Take an example and understand the concept of inheritance.

class parent:
    def f(self):
        print("parent class f method")
    def f1(self):
        print("parent class f1 method")

class child(parent):
    def f2(self):
        print("child class f2 method")
        
ob1 = child()
ob1.f2()
ob1.f1()
ob1.f()

In the above program, we had a class parent.

In the parent class, we have two methods, f, and f1.

We have one more class child. The child class is inheriting the parent class.

The definition for inheritance is given as class child(parent).

Inheritance means we can inherit the methods and variables of the class.

In our example, the child class inherits the parent class. The child class can access the parent class methods and variables.

We defined an object for child class and accessed the methods of parent class in the above program.

Multi-Level Inheritance

In our previous example, we inherited the parent class. This example is one level of inheritance.

If we inherit the class more than one level. We call multi-Level inheritance.

The example is given below.

class parent:
    def f(self):
        print("parent class f method")
    def f1(self):
        print("parent class f1 method")

class child(parent):
    def f2(self):
        print("child class f2 method")

class grandchild(child):
    def f5(self):
        print("this is grand child f5 method")

ob1=grandchild()
ob1.f5()
ob1.f2()
ob1.f1()
ob1.f()

In the above program, the child class inherits the parent class, and the grandchild class inherits the child class.

Grandchild class is having two levels of inheritance. It can access members in child class and parent class.

The above program is an example of multi-level inheritance.

Multiple Inheritance

Take an example and understand multiple inheritances.

class a:
    def f1(self):
        print("This is class a f1 method")

class b:
    def f2(self):
        print("This is class b f2 method")
        
class c(a,b):
    def f5(self):
        print("This is class c f5 method")

ob1 = c()
ob1.f1()
ob1.f2()
ob1.f5()

In the above program, we had a class a, and in-class a, we had a method f1.

We had class b. In class b, we had a method f2.

Class c is inheriting both classes a and class b. this type of inheritance we call multiple inheritance.

In multiple inheritance, we inherit more than one class.

Class c objects can access the members of the class a and class b.