Python Programming – Python Multiple Inheritance
Multiple inheritances refer to two or more base classes and one derived class. In this type of inheritance, the features of multiple classes can be inherited into the derived class. The programming example of multiple inheritances is given in Code 11.2. This program contains three classes, two base classes student and marks and one derived class result, which inherits the traits of both students and marks classes. The student class having two data members name and role of the student and a class function display, which displays the values of name and roll no. The other base class marks contain three data members ml, m2, and m3 representing marks of three subjects. It also contains a class function display_marks(), which displays the marks of all three subjects. Now, the third derived class result, which is derived from both the base classes student and marks contains two data members total_marks and perc representing percentage. It also contains a class function display_result() to display the total_marks and percentage of a student.
In this program, the object of the derived class result is created as r1. It is to be noted here that by the creation of object r1 the__init__() constructor method of derived class result is invoked automatically, which further invokes the constructor methods of base classes student and marks to initialize or input the values .of student name, roll no, and marks of three subjects. Subsequently, the total_marks and percentage are computed in the __init__() method of the derived class. Then display(), display_marks(), and, display_result() functions of the class student, marks, and the result are invoked by using the r1 object of result (derived) class. These functions display the appropriate output on the terminal.
Code: 11.2. Illustration of multiple inheritance.
|#illustration of multiple inheritance
class student: #base class 1
def display(self): #display method of base class 1
class marks: Case class 2
class result(student, marks): #derived class
rl=result() # object of derived class result
Enter Student Name: John
Marks of subject 1= 44.0
Marks of subject 2= 54.5
Marks of subject 3= 36.0
Total Marks: 134.5