In this Python lesson we want to learn about Python Multi Level Inheritance, in object oriented programming when you inherits a derived class from another derived class this is called multi level inheritance and it can be done at any depth.
Now let’s take a look at this image.
If you see in the above image we have three classes, we have a Class A, this class is our base class. we have another Class B, this class extends from the base Class A. we have another Class C, now this class extends from Class B. as we have already said when you extends a derived class from another derived class this is called multi level inheritance and it can be done at any depth. now our Class B can access to all attributes and method of the Class A, and our Class C can access to all attributes and methods of the Class A and Class B.
Now let’s create a practical example, in this example we have our base class that is class Person, in this class we have created a method. we have two more classes, one is class Student and it is extending from class Person, there is a method in this class. also we have another class that is class Programmer, this class extends from the Student class. now if you create the instance of the Programmer class, this class can access to the method of the Person and Student classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Person: def per_method(self): print("Iam a Person") class Student(Person): def stu_method(self): print("Iam a Student") class Programmer(Student): pass pro = Programmer() pro.per_method() pro.stu_method() |
Run the code and this is the result.
As i have already said you can create Python Multi Level Inheritance at any depth.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
class Person: def per_method(self): print("Iam a Person") class Student(Person): def stu_method(self): print("Iam a Student") class Programmer(Student): def pro_method(self): print("Iam a Programmer") pass class D(Programmer): pass pro = Programmer() pro.per_method() pro.stu_method() d = D() d.per_method() d.stu_method() d.pro_method() |