python


Multilple Inheritance

In this tutorial, we will learn about multiple inheritance and how to use it. We will also learn about multilevel inheritance.

Multiple inheritance in python

The concept of multiple inheritance in python is similar to C++.
Multiple inheritance is the inheritance in which a class is derived from more than one parent or base class.
In multiple inheritance, all the features of both base classes inherited to the derived class.
You can see an example below:

example of multiple inheritance
Syntax:
 class baseclass1:
    pass
class baseclass2:
    pass
class derived(baseclass1,baseclass2):
    pass
Example:
class Car:
    pass
class Truck:
    pass
class Engine(Car,Truck):
    pass

You can see above, we have 2 base classes Car and Truck from which a class Engine is derived.You can also pass methods in the class.

Multilevel Inheritance

In multilevel inheritance, we inherit from a base class and then also inherit another derived class from previous derived class.
It's a little bit confusing.Let's see the diagram:

multilevel inheritance
Syntax:
class base:
    pass
class Derived1(base):
    pass
classDerived2(Derived1):
    pass

In multilevel inheritance,the features of base class is inherited to first derived class and then the second derived class which is inherited from first derived class will consist of features of first derived class and base class.


Example:
 class Vehicle:
    pass
class Car(Vehicle):
    pass
class Engine(Car):
    pass

You can see above, here base class is Vehicle from which a class named Car is derived from which another class named Engine is derived.