From the start of this course, you may have noticed that I am not just teaching you the syntax so that you may learn just the practical approach to programming and could create a few programs that have no real-world value. Instead, I am trying to teach you all the theoretical and practical concepts together so you may become a successful programmer. You can do the programming by just learning the syntax, but without proper conceptual knowledge, you won't be able to develop proper logic while writing code. Our today’s tutorial is also based on a theoretical concept.
In previous tutorials, we have seen a lot of concepts related to Object-Oriented programming such as Single inheritance, Multiple Inheritance, Multilevel Inheritance, etc. Today we are going to discuss a problem or more like a confusion associated with multiple inheritance. The problem is commonly known as the “Diamond Shape Problem.”. It is about a priority related confusion, which arises when four classes are related to each other by an inheritance relationship, as shown in the image below:
Now we can see that the class C and class B are inheriting from class A, or it can be said as, class A is a parent to class B and C. And class D is inheriting from both class C and B. So, in a way they are all in relation to one and other somehow. Let us write down the relation in code format so it will be easier to understand.
class A: pass class B(A): pass class C(A): pass class D( B, C ): pass
As discussed earlier that it creates a priority related confusion, so lets clear that out here.
If the C class would be on left, such as
class D( C,B ): pass
Then priority would be given to C.
Sometimes, when we are working with too many classes, the concept of multiple inheritance could make our code more confusing and difficult to understand, such as:
You can see in the highlighted area that, it is a little difficult to understand which method is overriding which one, so multiple inheritance is discouraged in such situations.
class A: def met(self): print("This is a method from class A") class B(A): def met(self): print("This is a method from class B") class C(A): def met(self): print("This is a method from class C") class D(C, B): def met(self): print("This is a method from class D") a = A() b = B() c = C() d = D() d.met()
No downloadable resources for this video. If you think you need anything, please post it in the QnA!
Any Course related announcements will be posted here